即使我在服务器上启用了 CORS,Chrome CORS 仍然会阻止 API。我阅读了官方文档来启用CORS。我的后端是用 Nest.js 编写的,前端是用 Ionic/Angular 编写的。
除了官方文档之外,我还尝试了各种其他用户建议的解决方案,例如设置选项,但都不起作用。
使用 postman 时 API 调用工作得非常好。
这是服务器代码:
const app = await NestFactory.create(AppModule);
const options = {
origin: '*',
headers: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: true,
optionsSuccessStatus: 204,
credentials: true,
};
app.enableCors(options);
await app.listen(3000);
这是 http 调用:
this.http.post(`${this.config.serverAddress}/api/auth/login`,{'username': 'test', 'password': 'password'})
.subscribe(d=>{
console.log(d);
})
最后,这是 chrome 错误消息:
zone-evergreen.js:2952 Access to XMLHttpRequest at 'localhost:3000/api/auth/login' from origin 'http://localhost:8100' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
最佳答案
您的 URL 中缺少协议(protocol)。正如错误所述,仅支持以下协议(protocol):
http, data, chrome, chrome-extension, https.
因此尝试使用 http://localhost:3000/api/auth/login
关于javascript - 在服务器上设置请求后,Cors 仍然阻止请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57877198/