在带有node.js的jquery中使用get函数

编程入门 行业动态 更新时间:2024-10-10 01:25:31

在带有node.js的jquery中使用get<a href=https://www.elefans.com/category/jswz/34/1771370.html style=函数"/>

在带有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函数

本文发布于:2024-05-07 14:21:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756660.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   node   js   jquery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!