Search code examples
jquerynode.jspostexpresshttp-status

How to get the correct HTTP POST status code between Node.js express and jQuery client


In a Node.js app running Express, I have a route setup to take POST requests and create database objects.

app.post('/', function(req, res) {
    // create object in DB
    res.send('');
    res.status(201).end();
});

I understand a 201 status code indicates successful creation of the object. I wish to receive a 201 status in my jQuery POST on the client side:

$.post('/', sendData).done(function(receiveData, status, xhr) {
    alert(xhr.status); // returns 200 status
});

However, I am receiving a 200 status, not the 201 I am trying to send.

What can I change to receive at the client the 201 status code I am trying to send from the server?


Solution

  • From the docs

    Try setting the status before sending:

    app.post('/', function(req, res) {
        // create object in DB
        res.status(201).send('');
    });