简体   繁体   中英

How to get ExpressJs API CORS set up properly

I have a Single Page Application(SPA) using axios that tries to get information from a ExpressJS Api running on the same server.

In the SPA axios settings I have the following:

headers: {
 'Access-Control-Allow-Origin': '*',
 'Authorization': store.getters.token,
 'user': store.getters.user
},

and in the API i am using the npm package cors like this:

const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');

const app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());

const indexRouter = require('./routes/index');
const adminRouter = require('./routes/adminRoute');
// More routes

app.use('/api', indexRouter);
app.use('/api/admin', adminRouter);
app.use('/api/user', userRouter);
// using more routes

This works fine when running locally, but when putting the api on a server (using a node application) I get CORS errors:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at mysite.com. (Reason: CORS request did not succeed).

I can access the api directly from browser and get a response without problems (since it isn't using cross reference) but at least I know the API is running.

I have tried creating the following (before I define my routes) instead without success:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

What am I doing wrong?

It's really strange, to allow anything you have to just write app.use(cors()) and it should work probably now it dont work because after app.use(cors()) you write:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

then you should try with just cors() middleware. In order to set cors properly check cors`s documentation. Documentation

The reason why this did not work was because the web hotel where I hosted my ExpressJS api had not set up their nginx web server proxy so that it could accept the OPTIONS request properly and return with Access-Control-Allow-Origin: api.site.com

If you need more information regarding the setup of cors have a look at these links

CORS express not working predictably

How do I host a web application and an API from the same server while keeping them in separate?

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests

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