如何从 nodejs/express 向浏览器发送成功状态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13397691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:39:39  来源:igfitidea点击:

How can I send a success status to browser from nodejs/express?

formsnode.jspostexpress

提问by jansmolders86

I've written the following piece of code in my nodeJS/Expressjs server:

我在 nodeJS/Expressjs 服务器中编写了以下代码:

app.post('/settings', function(req, res){
    var myData = {
        a: req.param('a')
        ,b: req.param('b')
        ,c: req.param('c')
        ,d: req.param('d')
    }

    var outputFilename = 'config.json';

    fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
        if(err) {
          console.log(err);
        } else {
          console.log("Config file as been overwriten");
        }
    }); 
});

This allows me to get the submitted form data and write it to a JSON file.

这允许我获取提交的表单数据并将其写入 JSON 文件。

This works perfectly. But the client remains in some kind of posting state and eventually times out. So I need to send some kind of success state or success header back to the client.

这完美地工作。但是客户端仍然处于某种发布状态并最终超时。所以我需要将某种成功状态或成功标头发送回客户端。

How should I do this?

我该怎么做?

Thank you in advance!

先感谢您!

回答by ac360

Express Update 2015:

2015 年快速更新:

Use this instead:

改用这个:

res.sendStatus(200)

This has been deprecated:

这已被弃用:

res.send(200)  

回答by Aron Woost

Just wanted to add, that you can send json via the res.json()helper.

只是想补充一点,您可以通过res.json()助手发送 json 。

res.json({ok:true}); // status 200 is default

res.json(500, {error:"internal server error"}); // status 500
res.json(500, {error:"internal server error"}); // status 500

Update 2015:

2015 年更新:

res.json(status, obj)has been deprecated in favor of res.status(status).json(obj)

res.json(status, obj)已被弃用 res.status(status).json(obj)

res.status(500).json({error: "Internal server error"});

回答by user2468170

In express 4 you should do:

在 express 4 中,您应该执行以下操作:

res.status(200).json({status:"ok"})

instead of the deprecated:

而不是弃用的:

res.json(200,{status:"ok"})

回答by Samuel

Jup, you need to send an answer back, the simplest would be

Jup,你需要发回一个答案,最简单的就是

res.send(200);

Inside the callback handler of writeFile.

在 的回调处理程序中writeFile

The 200 is a HTTP status code, so you could even vary that in case of failure:

200 是一个 HTTP 状态代码,所以你甚至可以在失败的情况下改变它:

if (err) {
    res.send(500);
} else {
    res.send(200);
}