提问人:aasem shoshari 提问时间:9/10/2023 最后编辑:aasem shoshari 更新时间:9/10/2023 访问量:72
无论您设置了什么配置,CORS 策略都会阻止来自客户端的请求
Requests from Client is blocked by CORS Policy, no matter what configuration you set
问:
我在 Vercel 上部署了一个 MERN 应用程序,但您知道请求必须发生在客户端和 API 之间才能使网站运行,例如 、 等。signup
login
get-employees
app.get("/get-employees", (req, res) => {
employee.getEmployees(req, res);
});
调用此路由时,仅从数据库中获取一些对象,并在开发阶段进行测试。当然,我还制作了许多其他路线来为我的前端服务。employees
在客户端,我将使用 ,例如,我在我的 signup.js react 组件中创建了一个名为 的路由,并且该组件当然需要调用路由才能注册用户:fetch API
/signup
/signup
const handleSignup = async (e) => {
const user = {
username: username.current.value,
password: password.current.value,
};
await fetch("---/signup", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(user),
});
};
正如你在这里看到的,我已经部署了我的,我还制作了一条路线,只是为了确保它正常工作。我所做的只是发送请求以注册用户,但这会那么容易吗?当然不是,我们有一个叫做.API
Vercel
get
hello
/signup
CORS
因此,我将此代码添加到我的服务器端,以便从客户端进行访问:index.js
const corsOptions = {
origin: '---',
credentials: true,
}
app.use(cors(corsOptions))
但这并没有像预期的那样工作,所以我尝试了一种不同的方法:CORS
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // '*' allows any origin, you can restrict it to specific origins
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
next();
});
那也没有用。我还尝试启用所有源、所有方法和所有标头,但 CORS 拒绝了。
以下是我收到的错误:
/employees:1 Access to fetch at '---' from origin '---' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Failed to load resource: net::ERR_FAILED asyncToGenerator.js:6
Uncaught (in promise) TypeError: Failed to fetch
at AuthContext.js:21:28
at d (regeneratorRuntime.js:44:17)
at Generator.<anonymous> (regeneratorRuntime.js:125:22)
at Generator.next (regeneratorRuntime.js:69:21)
at r (asyncToGenerator.js:3:20)
at s (asyncToGenerator.js:22:9)
at asyncToGenerator.js:27:7
at new Promise (<anonymous>)
at asyncToGenerator.js:19:12
at AuthContext.js:20:21
答:
-1赞
aasem shoshari
9/10/2023
#1
看起来我需要为 Microsoft Edge 安装一个扩展程序,因为默认情况下是禁用的Allow CORS: Access-Control-Allow-Origin
CORS
评论