Amit
Amit

Reputation: 126

Cors issues if I send request with json in body

I have react running on localhost port 3000 and express running on port 8000. I want to do the following request from within react:

  fetch('http://localhost:8000/login', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(json), //this line cause cors problems
  })

but then I get the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

If I remove the body from the request the request actually works fine.

This ist my express server.

let app = express(); // Export app for other routes to use
let handlers = new HandlerGenerator();
const port = process.env.PORT || 8000;
//middlewares
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors()); 
//app.use(cors({origin:'http://localhost:3000'})); //restrict the origin to localhost doesn't work either
app.use( (req, res, next) => {console.log(req.body); next()});
// Routes & Handlers
app.options('/login', (req, res)=>{res.end()});
app.post('/login', handlers.login);
app.get('/', middleware.checkToken, handlers.index);
app.options('/', (req, res)=>{ res.end();} );
app.listen(port, () => console.log(`Server is listening on port: ${port}`));

Hope somebody can explain this. thanks Amit

Upvotes: 0

Views: 300

Answers (1)

user9408899
user9408899

Reputation: 4540

Move app.use(cors()) to on top of the other middlewares. Like this:

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

You have to allow cors, before processing the body of the request.

Upvotes: 2

Related Questions