Search code examples
node.jspostexpresshttp-headers

how to send just a 200 response in express.js


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


Solution

  • 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.