【发布时间】: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