Search code examples
javascriptnode.jsreactjsaxiosrestful-url

Axios Post Request is Not Working in React JS


I have used Postman to send Post requests and they are working fine but when I try to use axios it is giving me this error.


createAnimeList.js:27
 Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:83)
xhr.js:178 POST http://localhost:4000/animes/add 
net::ERR_CONNECTION_REFUSED

This is my backend code

router.post("/add", async (req, res) => {
  console.log("Heeeere");
  console.log(req.body.animeName);
  var anime = new Animes({
    animeName: req.body.animeName,
  });
  anime = await anime.save();
  return res.send(anime);
});

Here is my React code where I am using Axios

onSubmit(event) {
    event.preventDefault();
    const anime = {
      animeName: this.state.animeName,
    };
        console.log(anime);

    axios
      .post("http://localhost:4000/animes/add", anime)
      .then((res) => console.log(res.data))
      .catch((err) => console.log(err));

    //window.location = "/anime";
  }

Solution

  • you need to enable CORS( Cross-Origin-Resoruce-Sharing)

    you can either use the cors package

    https://www.npmjs.com/package/cors

    or this code

    place this controller before every controller in your application

    app.use((req, res, next) => {
      res.setHeader('Access-Control-Allow-Origin', '*'); // to enable calls from every domain 
      res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE'); // allowed actiosn
      res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); 
    
      if (req.method === 'OPTIONS') {
        return res.sendStatus(200); // to deal with chrome sending an extra options request
      }
    
      next(); // call next middlewer in line
    });