Search code examples
node.jsexpressserverclientresponse

Express send response and catch it in client


im trying to have the user send some data to the server, where it gets saved into a db, after this I would like to send a message back to the user (for example containing the id of the newly added object), but I was not yet able to succeed my code:

    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----
               })
            }
        })
    })
});

and this is the client side function that sends the new data, im also guessing there is a better way to do this, but this worked so far (however any feedback would be appreciated!)

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

thanks for any help in advance!


Solution

  • You can do it like this using 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
    });
    

    At the client side you can do this:

    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);
    }
    
    

    Check here for more details.