简体   繁体   中英

Setting up express + react, CORS

Hey I'm trying to make work my express with react locally. I'm starting react on localhost:3000 and express on 4040 but somehow my cors doesn't work. I have allowed in my server.js all cors stuff:

var allowedOrigins = ['http://localhost:3000',
    'http://127.0.0.1:3000', '*'];
app.use(cors({
    origin: function(origin, callback){
        // allow requests with no origin
        // (like mobile apps or curl requests)
        if(!origin) return callback(null, true);
        if(allowedOrigins.indexOf(origin) === -1){
            var msg = 'The CORS policy for this site does not ' +
                'allow access from the specified Origin.';
            return callback(new Error(msg), false);
        }
        return callback(null, true);
    }
}));


app.options('/attendant', function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader('Access-Control-Allow-Methods', '*');
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.end();
}); 

But still after trying to fetch data from express, in my react,I get:

Access to fetch at 'http://localhost/4040/attendant' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

What am I missing?

The order that you apply routes and middleware in matters.

You need to allocate the cors middleware before the route that requires it, otherwise it won't be run.

Since the Access-Control-Allow-Origin header is reported as missing, you must have assigned them in the other order.

Change the order:

app.use(cors()); // No need to use any options. "Everything" is the default, and you included everything in your list.
app.get('/attendant', (req, res) => res.send('Hello World!'))

By chance I might have spotted an error: your route '/attendant' must respond to a GET request. Try this and tell me if it works !

const express = require('express')
const app = express()

const cors = require('cors')

app.use(cors())

app.get('/attendant', function (req, res) {
  res.json({msg: 'It works'})
})

app.listen(4040, function () {
  console.log('Server running on port 4040')
})

Perhaps if you want to set options to your attendant route, you should use app.all()

app.all('/attendant', function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  next(); // pass control to the next handler
});

See these documentations for more: https://expressjs.com/fr/guide/routing.html and https://expressjs.com/en/resources/middleware/cors.html

You do not need CORS to communicate with your server. create-react-app has a feature called proxy . It allows you to proxy all of your requests to:4040

In package.json , add the following entry to the end:

"proxy":"http://localhost:4040"

Send your requests to your React server on:3000. Example: fetch('/api/example/') and it will work without having any CORS trouble

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM