node.js - 服务器不响应带参数的 url

标签 node.js express mongoose

我现在正在尝试创建一个服务器,应该能够注册用户。 但是,当尝试使用/reg 注册时,服务器不会使用react。 当我创建一个新的 .get 时,它确实响应,因此服务器本身正在工作。

我还不清楚如何正确设置 URL 格式。

app.post('/reg/:uname/:teamid', function(req, res){
  var username = req.params.uname;
  var teamidpar = req.params.teamid;

  UserSchema.pre('save', function (next) {
    this1 = this;

    UserModel.find({uname : this1.username}, function(err, docs) {
        if (!docs.length) {
            //Username already exists
        } else {
            var loginid = randomstring.generate();
            var newUser = User({
                uname : username,
                teamid : teamidpar,
                totalscore : 0,
                lastopponement : null,
                gamescore : 0,
            });

            User.save(function (err, User, next) {
                if (err) {return console.error(err);}
                else
                {console.log(timestamp+':'+'User created:'+newUser.uname+':'+newUser.login);}
                res.json({login : loginid});
            });   
         }
      });
   });
});

最佳答案

我不知道为什么我之前没有看到这个,但是你在开始时使用了UserSchema.pre,但这只是一个定义,不会立即执行。只有当您实际对文档进行保存时,才会触发此功能。

位于正确的、编辑后的版本下方。

app.post('/reg/:uname/:teamid', function(req, res) {
  var username = req.params.uname;
  var teamidpar = req.params.teamid;

  // If you are just checking if something exist, then try count 
  // as that has minimal impact on the server
  UserModel.count({uname : username}, function(err, count) {
    if (count > 0) {
      // Username already exists, but always output something as we
      // don't want the client to wait forever
      return res.send(500);
    }

    var loginid = randomstring.generate();

    // You'll need a new instance of UserModel to define a new document
    var newUser = new UserModel({
      uname : username,
      teamid : teamidpar,
      totalscore : 0,
      lastopponement : null,
      gamescore : 0,
    });

    // Save the document by calling the save method on the document
    // itself
    newUser.save(function (err) {
      if (err) {
        console.error(err);

        // You'll want to output some stuff, otherwise the client keeps on waiting
        return res.send(500);
      }

      console.log(timestamp + ': User created:' + username + ':' + loginid);
      res.json({login : loginid});
    });   
  });
});

关于node.js - 服务器不响应带参数的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30347432/

相关文章:

javascript - Electron App 中的 BrowserWindow 渲染

javascript - 如何在 NodeJS 中的 .txt 文件中添加新行文本

node.js - 如何启动expressjs(nodejs)作为生产模式

http - go 中的路由处理

node.js - Mongoose查询回调返回?

javascript - 如何在 Mongoose 中扩展查询对象

node.js - chai-http 结束后写入

javascript - 如何在 Knex JS 中使用 IS NOT NULL

javascript - Express、通配符子域和 sendFile()

javascript - 无法理解 async/await Nodejs