how to send just a 200 response in express.js
Asked Answered
P

2

41

I have node.js 5.2.0, express 4.2.0 and formidable 1.0.17.

I created a simple form to save a textfield and a photo. It works fine, but the problem is, after the data are uploaded, I can see in the console that the POST is not finished, its still Pending.

In order to finish it I added this to my code

form.on('end', function() {
    res.writeHead(200, {'Content-Type': 'text/plain'});
});

I just want to send the headers and nothing on the page. I want the system to get a 200 ok response without having to print anything on the page. But the POST is still pending.

How do I fix this, without having to print anything? What kind of headers I have to send?

Thanks

UPDATE

If I do

form.on('end', function() {
    res.end();
});

The POST finishes normally, but I get a blank page. Why is that? I just want to upload some stuff, not print anything on the page, not redirect, stay in the same page.

Thanks again

Playroom answered 14/12, 2015 at 19:42 Comment(1)
res.status(200).end('OK')Parabolize
A
78

Try this instead:

res.sendStatus(200);

Or if you want to continue using explicitly defined headers, I believe res.end() needs to be called at some point. You can see how res.end() is utilized in the Formidable example.

The blank page is most likely the result of your client-side form handling. You may want to override the form's submit method and manually post to your express service to prevent the automated redirection you are seeing. Here are some other stackoverflow responses to a question involving form redirection. The answers are jQuery specific, but the basic idea will remain the same.

Autotrophic answered 14/12, 2015 at 19:47 Comment(3)
Thanks. For some reason I get res.sendStatus is not a function. Also check my update. If I add res.end(); either in form.on or in form.parse , I still get a blank page after uploading. Can you please tell me why and how to fix this?Playroom
Hm. Are you sure about the express version? Here's a link to their docs for using sendStatus(). Maybe try .status(200).send('OK')? I also updated my main answer in regards to the blank page -- the issue is most likely client side at that point.Autotrophic
A yes, the redirecting is the default behaviour, just because I am using Node does not changes anything. Thank you so much, I will deploy AJAX for this.Playroom
L
1

Use:

res.status(200).json("your text");

If you want to display something as well as send status 200.

res.sendStatus(200);

Will only display ok in screen

Listed answered 23/6, 2023 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.