[NodeJS Express / React] API not working due to CORS

Hi there,
In my React app, I wanted to switch from my old PHP API to my new Node API. Unfortunately, it seems like there’s a bigger issue.

The back-end is already on a server, but while re-wiring to the new API I use Localhost.

In my react app for example I have:

        fetch('myurl/people/requests', {
            method: 'POST',
            headers: {
                'Authorization': cookies.get('accesstoken')
            body: JSON.stringify({
                "user_id": props.user,
                "mode":  cookies.get('gscover')
            .then(response => response.json())
            .then(data => {
                if (data.hasOwnProperty("data")) {
                else {

And in Node

var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var config = require('./side');
var mysql = require('mysql');
var usersRouter = require('./routes/user.routes');
var peopleRouter = require('./routes/people.routes');
var geoRouter = require('./routes/geography.routes');
var con = mysql.createConnection({
...connection data...

const PORT = process.env.PORT || 3001
var app = express();

This is not working. (please note that data inside variable con are working, I just hide it).
While looking for answers I have also tried

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');

app.use('/people', peopleRouter);

The latter one resulted in an error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://myapp/people/requests. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

There’s more that I have tried, but with no positive outcome. But it works using Postman. Due to the error, I considered first putting CORS into the routes, but then I thought it should be initialized when doing this in app.js.

I have now made changes to the front-end and uploaded it to see it in action as I read that Firefox may block localhost-requests. However, the problem remains.
But I have also made tests with ReqBin and RestClientOnline by ExtendsClass to test the connection in my browser. It works.

What could be the reason, how can I solve this?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.