如何在ajax发送请求时检索响应(XMLHtttpRequest)

时间:2017-11-17 18:49:45

标签: javascript node.js ajax express xmlhttprequest

/* 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?

大家好,

我的代码(前端)的顶部是一个以json格式发送请求的ajax。

我的代码(节点/快速服务器)的底部执行以下操作:    1)接收请求    2)插入" request.body"在数据库中    3)将响应发送回前端。

此响应是包含request.body的Promise。如何在我的前端代码中检索此响应?似乎ajax帮助我发送请求,但是没有做任何关于检索返回的响应的事情。

谢谢!

P.S。由于此数据最初是从前端发送的,因此可以说前端已经拥有此数据。但是,我只想知道如何在ajax发送请求时检索响应。

1 个答案:

答案 0 :(得分:-1)

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

xhr有一个事件处理程序 onreadystatechange , 您可以说xhr.readyState == XMLHttpRequest.DONE时请求已成功。

有关此问题的更详细的文档可以使用@ https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

您还可以从 xhr.status

获取http请求的状态代码

XMLHttpRequest是非常有用的API,但是它太低了,它现在被 FETCH API取代,这很棒,它也支持promise接口,这意味着你可以使用.then和.catch,或更新的async / await。

你可以在这里阅读@ https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

和一个例子@ https://googlechrome.github.io/samples/fetch-api/fetch-post.html