【发布时间】:2020-01-23 05:52:34
【问题描述】:
我已经在后端设置了 cors,我只是不知道为什么我在 url 正确时收到 404 错误。错误是访问来自源“http://localhost:3007”的“http://localhost:3008/api/vehicle”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。我还在下面添加了我的 api 跨域。请检查下面的示例代码。这个问题的解决方案是什么?是什么导致了这个问题?我已经在后端设置了 cors,我只是不知道为什么我在 url 正确时收到 404 错误。错误是从源“http://localhost:3007”访问 XMLHttpRequest 在“http://localhost:3008/api/vehicle”已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。我还在下面添加了我的 api 跨域。请检查下面的示例代码。这个问题的解决方案是什么?是什么导致了这个问题?
有什么想法吗?
Http 发布服务
save(vehicle: Vehicle){
return this.http.post(
CONSTANST.routes.person.save,
{
Stock: vehicle.Stock,
VIN: vehicle.VIN,
age: vehicle.age,
gender: vehicle.gender,
},
);
}
路线
const HOST ='http://localhost:3008'
export const CONSTANST = {
permissions:{},
routes:{
authorization:{
login: HOST + '/api/app/signin-email',
logout: HOST + '/api/auth/logout'
},
person:{
list: HOST + '/api/vehicle',
save: HOST + '/api/vehicle',
},
user: {}
},
lang:{},
session:{},
parameters:{}
};
api跨域请求
if (process.env.NODE_ENV !== 'production') {
console.log('------------------------------------------------');
console.log('Notice: Enabling CORS for development.');
console.log('------------------------------------------------');
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
}
api 路由
app.get('/api/vehicle', keystone.middleware.api, routes.api.vehicle.list);
app.post('/api/vehicle', keystone.middleware.api ,routes.api.vehicle.create);
【问题讨论】:
-
UI和API的端口不同。因此它将被浏览器安全阻止。 API 必须发送值为
*或http://localhost:3007的 Access-Control-Allow-Origin 标头以绕过此 -
请在此处显示您的后端 cors 配置...
-
我建议在开发过程中使用 Angular 代理配置(github.com/angular/angular-cli/blob/master/docs/documentation/…)而不是使用完整 URL 直接 API 调用。添加代理后,您无需添加主机,如
HOST + -
那么解决方案是什么?
-
@ArifKhan,直接用完整的URL调用api有什么坏处?
标签: javascript node.js angular cors