【问题标题】:How to retrieve a response when the request is sent by ajax (XMLHtttpRequest)ajax发送请求时如何获取响应(XMLHttpRequest)
【发布时间】:2018-05-01 15:04:47
【问题描述】:
/* 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 可以帮助我发送请求,但对检索返回的响应没有任何作用。

谢谢!

附:由于这个数据最初是从前端发送的,所以有人可能会说前端已经有了这个数据。但是,我只想知道,一般来说,当请求由 ajax 发送时,如何检索响应。

【问题讨论】:

  • 提示:如果您不listen for it,您将永远不会听到回复
  • @maioman 感谢您富有洞察力的评论!

标签: javascript node.js ajax express xmlhttprequest


【解决方案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

【讨论】:

  • 这个答案可能是正确的,但它会从解释中受益。
  • @Ankur 好的,所以想法是监听“DONE”事件,然后调用“xhr.responseText”。有效。谢谢!
猜你喜欢
  • 2016-11-28
  • 1970-01-01
  • 2011-12-21
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多