gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:26:04 26 4
gpt4 key购买 nike

我现在正在尝试创建一个服务器,应该能够注册用户。但是,当尝试使用/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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com