我正在写一个服务器,并在发布后将它保存到一个带有fs的文件中。Nodejs post不断加载
客户端页面继续加载提交,写文件是否需要异步,如果是的话,回调看起来像什么,为什么页面仍然加载。
app.post('/', function(req,res) {
console.log(req.body)
fs.writeFileSync('data.txt', JSON.stringify(req.body))
})
这是因为我没有回复?
我正在写一个服务器,并在发布后将它保存到一个带有fs的文件中。Nodejs post不断加载
客户端页面继续加载提交,写文件是否需要异步,如果是的话,回调看起来像什么,为什么页面仍然加载。
app.post('/', function(req,res) {
console.log(req.body)
fs.writeFileSync('data.txt', JSON.stringify(req.body))
})
这是因为我没有回复?
是的,这是因为你没有发送回应。 Express不会自动发送响应,因此当您发布到该端点时,您必须返回响应,否则请求将挂起。
文件写入不必是异步的,但它应该是。现代的方式做,这是使用的承诺,像...
new Promise(function(resolve, reject) {
fs.writeFile('data.txt', JSON.stringify(req.body), (err) =>
{
if (err) reject(err);
else resolve(data);
}
}).then(
(success) => res.send(success)
).catch(
(err) => {
console.log(err);
res.status(500).send();
}
);
如果你不想这样做异步(你不需要,如果它是一个低性能的网站),只是做:
app.post('/', function(req,res) {
console.log(req.body)
fs.writeFileSync('data.txt', JSON.stringify(req.body))
res.send({"status": 200});
})
你的代码是罚款,除了忽略发送回应。如果您没有通过发送响应或手动呼叫res.end()
来终止连接,则服务器将挂起,发出请求的客户端将超时。
调用res.send()
将为您结束连接,并向客户端发送响应,让他们知道至少请求的状态。
只发送一个字符串不应该导致页面重新加载。
app.post('/', function(req,res) {
console.log(req.body)
fs.writeFileSync('data.txt', JSON.stringify(req.body))
// Set status code to 200, send string response
res.status(200).send('Ok');
})
好吧,发送响应并将其更改为异步函数将提高我的服务器? – Sprout
是。人们会告诉客户端服务器正在处理请求,另一个会阻止所述路由成为整个服务器的巨大瓶颈。 –
因此,当我发送回应时,它会更改为另一个页面,我想发送回复但保持在同一页面上。那可能吗? – Sprout