我在从端口 3000 上运行的前端向端口 4000 上运行的 Express 服务器发出 HTTP POST 请求调用时遇到问题。我正在使用 mongoDB 并进行调用来存储我的表单数据。当我检查控制台的 newtork 选项卡时,我看到 CORS 错误,因此我应用了 cors 中间件,但即使这样,也会出现一些错误,说明 prefilght 请求存在问题。我也应用了预检配置,但仍然无法在我支持的 API 路由上进行调用。我在网上查看,它说要向预检请求应用一些标头,但我无法执行此操作。请帮忙
const savedResponse = await fetch(
`http://localhost:4000/api/createuser`,
{
method:"POST",
headers:{
"Content-Type":"application/json",
},
body:JSON.stringify({...data})
}
// Configure the cors options with preflight handling
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: ['GET', 'POST', 'PUT', 'DELETE'], // Add other methods you need to support
allowedHeaders: ['Content-Type', 'Authorization', "Access-Control-Allow-Origin",
"Access-Control-Allow-Methods","Access-Control-Allow-Headers"], // Add other custom headers you need to support
optionsSuccessStatus: 200, // Some legacy browsers (IE11, various SmartTVs) choke on 204
};
// Apply the cors middleware with the specified options
app.use(cors(corsOptions));