'CORS issue when changing to ES6 import versus require
My Vue app has a backend with a different url to the front end.
In my backend (node) I am using the cors module.
My app is a standard express app and I was using for example:
const express = require("express")
Everything was 100% fine.
I then changed to ES6 and used import like:
import express from "express";
On my localhost everything is spot on however when I deploy I am getting the cors error as per below. (it was fine with the old javascript)
blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My app.js looks like so:
import EventEmitter from "events"
import dotenv from "dotenv"
dotenv.config()
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
import { dirname } from "path";
import path from 'path';
import pool from './routes/connection.js'
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
import chalk from "chalk";
import cookieParser from "cookie-parser";
import session from "express-session";
const app = express()
const port = process.env.PORT || 3000;
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type', 'Authorization', 'authorization'],
'exposedHeaders': ['sessionId'],
'origin': ['https://eccentrictoad.com', 'https://www.eccentrictoad.com'],
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'credentials': false,
'preflightContinue': false
}));
const emitter = new EventEmitter()
emitter.setMaxListeners(0)
app.use(express.static(path.join(__dirname, "/server/public")));
import progressRoutes from "./routes/progressRoutes.js";
import progressResultsRoutes from "./routes/progressResultRoutes.js";
import userRoutes from "./routes/userRoutes.js";
import updateRoutes from "./routes/updateRoutes.js"
app.use(progressRoutes,
progressResultsRoutes,
userRoutes,
updateRoutes
);
I could simply revert back to the old style of doing it using "require" but I would really like to figure out why it is an issue.
I am deployed on an Apache Server
Solution 1:[1]
import dotenv from "dotenv"
should be import dotenv from "dotenv/config"
. Also remove dotenv.config()
.
That should do it. ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | doge__whisperer |