一种将数据从服务器发送到js文件的方法

时间:2020-05-17 06:46:45

标签: javascript node.js

我最近开始了一个项目,我需要将数据从服务器端(node.js)转换为我的js文件(在客户端上,我正在使用常规js)。有什么办法吗?

服务器:

app.get('/start', function (req, res) {
console.log("enter");
res.sendFile(path.join(__dirname, 'client', 'enter.html'));
});

app.post('/start', function (req, res) {
const userName = req.body.userName;
const userPassword = req.body.password;

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 {
        res.status(200).send({ message: "Hello!" });
    }
});
});

我想通过js文件(在客户端中)获取消息

1 个答案:

答案 0 :(得分:0)

您可以尝试

fetch('/start', {
  method: 'POST', 
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({username : 'test'}),
})
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});
相关问题