Reputation: 33
I got the error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at localhost:...
with my examples code below, how can I fix it?, I just follow any guides in docs and stackoverflow but no one working.
I'm using cors module from npm.
// Init express application
const app = express();
// Setup cors for cross domain requests
const whitelist = [
"http://localhost:3002/", // frontend curr localhost port
"http://localhost:5500/", // live server url
];
// eslint-disable-next-line
const corsOptions = {
origin: function (origin, callback) {
// allow if the origin is undefined,
// means has the same origin, the result
// is undefined because the request
// is coming from the same origin.
if (!origin) return callback(null, true);
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error("CORS not allowed"));
}
},
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
methods: ["GET", "PUT", "POST", "DELETE", "OPTIONS"],
credentials: true, //Credentials are cookies, authorization headers or TLS client certificates.
allowedHeaders: [
"Content-Type",
"Authorization",
"X-Requested-With",
"device-remember-token",
"Access-Control-Allow-Origin",
"Origin",
"Accept",
],
};
app.options("*", cors(corsOptions));
app.use(cors(corsOptions));
// END SECURITY CONFIG
// Route for monolithic app
const web = require("./routes/web");
// Route for microservices app
const api = require("./routes/api");
// Route for unit testing
const test = require("./routes/test");
Upvotes: 2
Views: 6438
Reputation: 46813
You can't fix this issue in code. It's a configuration issue for your network architecture, and your webbrowser is enforcing proper security.
For quite some time webbrowsers default to not allowing CORS for localhost.
The incorrect work-around is to disable CORS checking in your webbrowser. For Chrome it was adding the --disable-web-security
to the program executable, i.e. creating a chrome shortcut (Windows) to "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security
.
The correct way to resolve this is to not have your client code running on the webbrowser connect to your api server using localhost, and instead properly configure your environment to expose the server over a hostname.
There are a myriad of ways to do this depending on how you are running your server and clients, but if you are simply running your client and server on the same machine for development and debugging, you should only need to add an entry to your to your hosts file that resolves a hostname in addition to localhost to 127.0.0.1.
Then update your code to whitelist test.mydomain.com
127.0.0.1 localhost
127.0.0.1 test.mydomain.com
Upvotes: 5