Search code examples
javascriptnode.jsajaxexpressxmlhttprequest

How to retrieve a response when the request is sent by ajax (XMLHtttpRequest)


/* the following **frontend** function is invoked to 
   send a new post (in json) to the node server */

addPost(postData) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', `${process.env.REACT_APP_BACKEND}/posts`);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify(postData));
}

/* the following **server** code picks up the request 
   from the function above */

app.post('/posts', bodyParser.json(), (request, response) => {
    new Promise(resolve => {
            // code to add request.body to database will be here
            resolve(request.body);
        })
        .then(data => response.send(data)); // *** How do I retrieve
    }                                       // *** this "data" in
);                                          // *** my frontend code?

Hi all,

The top part of my code (frontend) is an ajax that sends a request in json format.

The bottom part of my code (node/express server) does the following: 1) receives the request 2) inserts "request.body" in a database 3) sends a response back to the frontend.

This response is a Promise containing the request.body. How do I retrieve this response in my frontend code? It seems that ajax helps me send requests, but doesn't do anything about retrieving the response that comes back.

Thanks!

P.S. Since this data was originally sent from the frontend, one might say the frontend already has this data. However, I just want to know, in general, how to retrieve a response when the request is sent by ajax.


Solution

  • const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            console.log(xhr.responseText);
        }
    }
    

    xhr has an event handler onreadystatechange , you can say that the request has been successful when xhr.readyState == XMLHttpRequest.DONE.

    more detailed doc on this can be availed @ https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

    you can also get the status code of the http request from xhr.status

    XMLHttpRequest is pretty Useful API, but it is too low level, it is now being superseded by FETCH API, which is awesome, it also supports promise interface, that means you can use .then and .catch , or the newer async/await.

    you can read it up here @ https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

    and an example @ https://googlechrome.github.io/samples/fetch-api/fetch-post.html