[英]How to fix ''http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.'
I am currently working on a react app but when I run yarn start.我目前正在开发一个 React 应用程序,但是当我运行 yarn start 时。 I keep getting this issue Access to XMLHttpRequest at ' https://google.com/ ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.我不断收到此问题访问 XMLHttpRequest at ' https://google.com/ ' 从来源 ' http://localhost:3000 ' 已被 CORS 政策阻止:不存在 'Access-Control-Allow-Origin' header在请求的资源上。
'web-preferences': { 'web-security': false } 'web-preferences': { 'web-security': false }
but the Moesif Orign & CORS Changer extension on chrome helped me bypass it but I am trying to fix it without an extension.但是 chrome 上的 Moesif Orign & CORS Changer 扩展帮助我绕过了它,但我试图在没有扩展的情况下修复它。
const electron = require("electron");
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require("path");
const isDev = require("electron-is-dev");
let mainWindow;
let createWindow=()=> {
mainWindow = new BrowserWindow({ width: 900, height: 680 });
mainWindow.loadURL(
isDev
? "http://localhost:3000"
: `file://${path.join(__dirname, "../build/index.html")}`
);
mainWindow.on("closed", () => (mainWindow = null));
}
app.on("ready", createWindow);
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (mainWindow === null) {
createWindow();
}
});
I am expecting to bypass this issue with out the Moesif Orign & CORS Changer extension on chrome.我希望在 chrome 上使用 Moesif Orign & CORS Changer 扩展绕过这个问题。
I faced the same problem using expressjs and it's basically the same, here's the code I've used to deal wit CORS我使用 expressjs 遇到了同样的问题,它基本上是一样的,这是我用来处理 CORS 的代码
const express = require('express')
const app = express()
// Defining CORS
app.use(function(req, res, next) {
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type"
);
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});
hope this helps希望这可以帮助
Run npm i --save cors
on the server, then在服务器上运行npm i --save cors
,然后
app.options("*", cors());
app.use(cors());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.