函数"/>
在带有node.js的jquery中使用get函数
我在将信息从后端(node.js)传递到前端(js文件)时遇到问题。我想做的是在服务器中从数据库(MongoDB)中获取信息,并将其传递到js文件中。问题是传递信息时出了点问题,我得到的是未定义的而不是“找到的”。
服务器:
app.post('/', function (req, res) {
const userName = req.body.userName;
const userPassword = req.body.password;
//building a new user if not exist
User.findOne({ userName: userName }, function (err, foundUser) {
if (foundUser === null) { //the subject doesnt exist yet
const newUser = new User({
userName: userName,
userPassword: userPassword,
});
newUser.save();
} else {
// the problem is here
console.log("exist");
res.json({ text: 'found' });
}
});
});
客户:
var msgFromServer;
$.get("/", function (data) {
msgFromServer = data.text;
console.log(msgFromServer);
alert("Received data from server!");
});
回答如下:app.post('/', function (req, res) {
const userName = req.body.userName;
const userPassword = req.body.password;
//building a new user if not exist
User.findOne({ userName: userName }, function (err, foundUser) {
if (foundUser === null) { //the subject doesnt exist yet
const newUser = new User({
userName: userName,
userPassword: userPassword,
});
newUser.save();
} else {
// the problem is here
console.log("exist");
res.json({ text: 'found' });
}
});
这是使用Express的默认'post'操作,因为您的JS客户端调用了默认路由'get'操作,您可以在此处发布它吗?
更多推荐
在带有node.js的jquery中使用get函数
发布评论