快速发送响应并在客户端捕获它

Express send response and catch it in client

我正在尝试让用户向服务器发送一些数据,然后将其保存到数据库中,在此之后我想向用户发回一条消息(例如包含新添加对象的 ID ), 但我还不能成功我的代码:

    router.post('/sendSnippet', function (req, res) {
    req.on('data', function(data) {
        User.findOne({email: req.user.email}).then((userToEdit) =>{
            if(userToEdit){
                var newSnippet = {
                    "types":[],
                    "code": data.toString()
                }
                userToEdit.snippets.push(newSnippet)
                userToEdit.save().then(()=>{
                    res.redirect('/profile/');
                    ----send response here----
               })
            }
        })
    })
});

这是发送新数据的客户端功能,我也猜想有更好的方法来做到这一点,但目前为止这个方法有效(但是,我们将不胜感激!)

function sendSnippet(){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open('POST', '/profile/sendSnippet', true);
    xmlHttp.send(data to send);
}

提前感谢您的帮助!

你可以这样使用 async/await:

   router.post('/sendSnippet', async (req, res) => {

    const userToEdit = await User.findOne({email: req.user.email});
    if (userToEdit) {
       var newSnippet = {
                    "types":[],
                    "code": data.toString()
    }
     userToEdit.snippets.push(newSnippet);
     const results = await userToEdit.save();
     res.send({results: results._id});// it will send response
});

在客户端你可以这样做:

function sendSnippet(){
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState === 4) {
      console.log(xmlHttp.response);
    }
  }

    xmlHttp.open('POST', '/profile/sendSnippet', true);
    xmlHttp.send(data to send);
}

查看 here 了解更多详情。