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

Formsnode.jsPostExpress

Forms Problem Overview


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

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.

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!

Forms Solutions


Solution 1 - Forms

Express Update 2015:

Use this instead:

res.sendStatus(200)

This has been deprecated:

res.send(200)  

Solution 2 - Forms

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

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

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

Update 2015:

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

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

Solution 3 - Forms

In express 4 you should do:

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

instead of the deprecated:

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

Solution 4 - Forms

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

res.send(200);

Inside the callback handler of writeFile.

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjansmolders86View Question on Stackoverflow
Solution 1 - Formsac360View Answer on Stackoverflow
Solution 2 - FormsAron WoostView Answer on Stackoverflow
Solution 3 - Formsuser2468170View Answer on Stackoverflow
Solution 4 - FormsSamuelView Answer on Stackoverflow