Home > Mobile >  How to get 201 status when uploading a file?
How to get 201 status when uploading a file?

Time:10-02

I'm building a react app with node.js (express && multer) and mongodb. When i upload a pic - the file is stored in a folder and the object is created in mongodb, but i get a 200 status instead of 201. What should i add to get the correct status?

     fetch("http://localhost:8080/addItems", {
       method: "POST",
       body: data,

   })
     .then(res => res.status !== 201 ? setFileExistsError(true) : setFileExistsError(false))
     };

return(
<>
        {fileExistsError && <p className="errorMsg">Item already exists</p>}
</>
)

CodePudding user response:

I have tried a post request with 201 status code on my node.js - react code and it worked. Your node.js code, should tell your react code that the status is "201".

  1. First, with your node.js, it should be something like this:
app.post("/addItems", function(req, res){
  myCollection.create(req.body).then(() => {
    res.status(201).end();
  });
});
  1. then, with your react.js (there is extra comma after data, and extra curly brace under then in your code. You should clean them as well):
fetch("/addItems", {
  method: "POST",
  body: data
})
.then ((res) => {
  if (res.status !== 201) {
    setFileExistsError(true);
  } else {
    setFileExistsError(false);
  }
})

return(
<>
   {fileExistsError && <p className="errorMsg">Item already exists</p>}
</>
)
  • Related