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?