Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sometimes GET returns 304 instead of 200

Tags:

node.js

I am using node.js and mongodb.

I seem to be receiving a 200 sometimes, and a 304 not modified other times.

router.get('/add-to-bag/:id', (req, res, next) => {
    req.session.bag.push(req.params.id);
    res.redirect('back');
    });
});
like image 658
Troy Avatar asked Jun 27 '17 20:06

Troy


3 Answers

I can't be sure what stack you're using to create the app. It looks like you're using Express.js to do routing. However, I can tell you why you're getting a 304.

From Wikipedia:

304 Not Modified (RFC 7232)
Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match. In such case, there is no need to retransmit the resource since the client still has a previously-downloaded copy.[24]

A 304 means "hey, remember the last answer I sent you? It hasn't changed", and hence your browser would replay the last response it received from cache, without data transmission ever having taken place.

This means that your data is being added. But since it's the exact same data in the bag, instead of giving a 200 with the exact same data again, the server just issues a 304.

BTW: Your API isn't Restful. I'd recommend using POST to create new records instead of issuing a GET to a different URL. I recommend reading up on REST API design. It's pretty straightforward once you get the hang of it.

like image 127
Amin Shah Gilani Avatar answered Oct 15 '22 12:10

Amin Shah Gilani


TL;DR: Use a POST request instead of a GET request.

GET requests should be used for getting things. A GET request should not affect the state of the application (i.e. of the server).

In your case, adding an item to the shopping bag is clearly a modification of the state of the server.

If you're not convinced, check out this answer

A GET is defined in this way in the HTTP protocol. It is supposed to be idempotent and safe.

If you use a POST request, not only will it fix you 304 issue, but it will also prevent some other possible bugs later on. (And it will be more correct.)

like image 38
Aurélien Gasser Avatar answered Oct 15 '22 14:10

Aurélien Gasser


Did you try by disabling etag?

app.disable('etag');
like image 27
jcdsr Avatar answered Oct 15 '22 12:10

jcdsr