无论您设置什么配置,来自客户端的请求都会被 CORS 策略阻止

问题描述 投票:0回答:1

我在 Vercel 上部署了一个 MERN 应用程序,但您知道请求必须在客户端和 API 之间发生才能使网站正常运行,例如

signup
login
等。例如,我创建了一条名为
 的发布路由get-employees

app.get("/get-employees", (req, res) => {
    employee.getEmployees(req, res);
});

此路由在调用时仅从数据库中获取一些

employees
对象,并且这在开发阶段进行了测试。当然我还做了很多其他的路线来服务我的前端。

在客户端,我将使用

fetch API
调用这些路由,例如,我在我的
signup.js
React 组件中创建了一个名为 /signup 的路由,并且该组件当然需要调用
/signup
路由为了能够注册用户:

const handleSignup = async (e) => {
    const user = {
        username: username.current.value,
        password: password.current.value,
    };
    await fetch("emp-dashboard-api.vercel.app/signup", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(user),
    });
};

如您所见,我已在

API
上部署了
Vercel
,并且还制作了一条
get
路线,上面写着
hello
只是为了确保其正常工作。我所做的就是向
/signup
发送请求来注册用户,但这有那么容易吗?当然不是,我们有一个叫做
CORS
的东西。

因此,我将此代码添加到服务器端的

index.js
中,以便能够从客户端进行访问:

const corsOptions = {
    origin: 'emp-dashboard-client.vercel.app',
    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 'https://emp-dashboard-api.vercel.app/get-employees' from origin 'https://emp-dashboard-client.vercel.app' 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.
emp-dashboard-api.vercel.app/get-employees:1 
        
        
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
cors fetch vercel w3c cross-origin-resource-policy
1个回答
0
投票

看起来我需要为 Microsoft Edge 安装扩展

Allow CORS: Access-Control-Allow-Origin
,因为
CORS
默认情况下处于禁用状态

© www.soinside.com 2019 - 2024. All rights reserved.