【问题标题】:Express send response and catch it in client快速发送响应并在客户端捕获它
【发布时间】:2021-08-21 20:32:21
【问题描述】:

我试图让用户向服务器发送一些数据,然后将其保存到数据库中,之后我想向用户发送一条消息(例如包含新添加对象的 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);
}

提前感谢您的帮助!

【问题讨论】:

    标签: node.js express server client response


    【解决方案1】:

    您可以使用 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了解更多详情。

    【讨论】:

    • 感谢您的回复!我自己到目前为止,但我现在的问题是:我如何“拦截”数据,例如 console.log 在客户端?
    • 是的,将事件附加到 XHR 对象。我已经更新了答案,你可以查看。
    猜你喜欢
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 2021-04-27
    • 2017-07-03
    相关资源
    最近更新 更多