0

i got these two CORS error (that is normally easy to fix) when i make a POST request (with a body preciselly), the other requests all works well.

I checked the content of my this.state.filter it's always in a good format. I also tested the route with Postman, with the same body that my front put in the request and it works good.

Even if the body is empty but present i got the errors, but if i don't put any second argument on the axios post method call and readapt my back to not use the req.body, it will works (the response will just not be what i really want).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/cat/filterlist. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/cat/filterlist. (Reason: CORS request did not succeed). Status code: (null)

My back-end in node.js with express (The Access-Control-Allow-Origin header is there):

router.post("/filterlist", function (req, res, next) {
  func.getFilteredList(req.body, (result) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.send(result);
  });
});

And my front-end in react with axios to make the request :

applyFilter = () => {
  console.log(this.state.filter);
  axios
    .post("http://localhost:3001/cat/filterlist", this.state.filter)
    .then((data) => {
      console.log(data.data);
      // this.setState({ cats: data.data });
    })
    .catch((error) => {
      console.log(error);
    });
}

This case without the second argument (the body) in the axios method call and a empty array to replace the request body req.body, will works but the function no longer makes sense -_- :

router.post("/filterlist", function (req, res, next) {
  func.getFilteredList([], (result) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.send(result);
  });
});
applyFilter = () => {
  console.log(this.state.filter);
  axios
    .post("http://localhost:3001/cat/filterlist")
    .then((data) => {
      console.log(data.data);
      // this.setState({ cats: data.data });
    })
    .catch((error) => {
      console.log(error);
    });
}

I will be very thankful if someone can solve my issue ;(.

Yukio
  • 25
  • 5

1 Answers1

1

install cors: $ npm install cors

var express = require('express')
var cors = require('cors')
var app = express()
 
app.use(cors())

this will enable CORS for all requests on your server. I hope this hepled!

ThePaulin
  • 67
  • 3