Stack:
NodeJS + Express + Firebase - BE
VueJS, Vuex, Axios (for api calls) - FE
Error I am constantly getting from dev & production environment:
Access to XMLHttpRequest at 'https://www.url.com/api/do-something' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Good to note: I am using new netlify function to “host” my BE APIs.
BE Code (server.js):
const express = require('express');
const bodyParser = require('body-parser');
const rateLimit = require('express-rate-limit');
const cors = require('cors');
const app = express();
const router = express.Router();
const admin = require('firebase-admin');
const serverless = require('serverless-http');
require('dotenv').config({path: __dirname + '/server.env'});
const port = 8002;
// Firebase config
...
const serviceAccount = require('../secret_path.json');
// Init the firebase app
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
const db = admin.firestore();
const limiter = rateLimit({
windowMs: 60 * 60 * 1000,
max: 3, // max requests
message: 'Too many requests to this endpoint. Please try again later.'
});
// Cors
const corsOptions = {
origin: '*',
credentials: true,
optionSuccessStatus: 200
}
app.use(cors(corsOptions))
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: true }));
app.set('trust proxy', 1);
// Set the main route
router.get('/api', (request, res) => {
res.send(`Beginning`);
});
// POST - Do something fun
router.post('/api/do-something', limiter, async (req, res) => {
const data = {
something: req.body.something,
};
try {
// if successfull:
return res.status(201).json({
success: true,
msg: 'Good'
});
} catch (err) {
return res.status(400).json({
success: false,
msg: `Error`
});
}
});
app.use('/', router);
app.listen(port);
module.exports = app;
module.exports.handler = serverless(app);
That is pretty much it for the BE part.
For the front-end part, I am handling the do-something API like so:
async coolEndpoint({ state, commit }, payload) {
let result;
try {
result = await axios({
headers: {
'Access-Control-Allow-Origin': '*',
Accept: 'application/json',
'Content-Type': 'application/json'
},
url: 'https://www.url.com/api/do-something',
data: {
something: payload.something
},
method: 'POST'
});
} catch (err) {
console.error(err);
}
return result;
}
And calling it on the FE through Vuex helpers (not relatable for this).
Also have setup redirects:
[build]
base = "/"
publish = "/dist"
functions = "functions"
command = "npm install && npm run build"
[dev]
port = 8081
publish = "/server"
command = "npm run start"
[[redirects]]
from = '/api/*'
to = '/.netlify/functions/server/:splat'
force = true
status = 200
[functions]
directory = "functions"
From dev & prod environments, I am calling the API url directly from where it is hosted, which netlify handles. Ex: https://www.url.com/api/do-something
(my domain)
And no matter from where do I call it, localhost or production through the same domain, it is constantly throwing the CORS error.
I also did setup a proxy in vue.config
file like a so proxy: 'https://www.url.com/'
.
Really could use some help as I’ve been struggling with this for month and a half (lol), and If any other info is needed I am here to edit and add.