Thunder Cat King
Thunder Cat King

Reputation: 662

Axios request always sends back 200

I'm making a very simple PUT request (see below.) For some reason no matter what response code I send back from my express server axios sees 200. In my express logs, it shows the correct response:

PUT /v1/org/password/reset 404 339.841 ms - 71

This is the line of code sending the response server side:

res.json({ message: 'Could not find user with that token or the token expired.' }).status(404);

I know this line is being triggered because the body logged to the browser console shows that same message. See screenshot.enter image description here

The only thing I can think of is the browser is caching the response?

    axios.put(`http://localhost:3000/v1/org/password/reset`, {
     password: "example",
     token: "19u8e8j2039d3d32blahblah"
   })
 .then(function (response) {
   if(response.status == 200){
       console.log("success",response)
     //handle success here
   }
 })
 .catch(function (error) {
   console.log("error", error);
   //handle error here
 });

Upvotes: 1

Views: 10091

Answers (2)

Alex
Alex

Reputation: 2126

The problem is on the backend side. Try to return response this way:

res.status(404).json({ message: 'Could not find user with that token or the token expired.' });

According to Express 4 documentation - https://expressjs.com/en/4x/api.html

Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.

So when you invoke "send" method Express writes out the http body content to the response, that's why first you need to fill headers.

Upvotes: 2

RedJandal
RedJandal

Reputation: 1213

try setting the status first like so

res.status(404).json({ message: 'Could not find user with that token or the token expired.' });

Upvotes: 2

Related Questions