【发布时间】:2018-06-12 16:57:53
【问题描述】:
我的前端使用 Angular,后端使用 Express。我遇到了一个 CORS 问题,其中 一个 具有类似配置的几个 api 端点:
无法加载http://localhost:3000/api/deletePost:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:4200' 不允许访问。响应的 HTTP 状态代码为 400。
任何帮助将不胜感激。谢谢。
前端代码(web-calls.service.ts):
// Not working
deleteArticle(articleId:string): Observable<any> {
return this.http.post('http://localhost:3000/api/deletePost', JSON.stringify(articleId), {
headers: new HttpHeaders().set('Content-Type', 'application/json'),
}).map(data => {
if (data["status"] == 200) {
this.router.navigate(['posts']);
} else if (data["status"] == 500) {
// TODO: error message and handling here
console.log(data);
}
return data["status"];
});
}
// working
createOrUpdatePost(url, articleComplete): Observable<number> {
return this.http.post('http://localhost:3000/api/updatePost', JSON.stringify(articleComplete), {
headers: new HttpHeaders().set('Content-Type', 'application/json'),
}).map(data => {
if (data["status"] == 200) {
this.router.navigate(['post' + '/' + data["response"]]);
} else if (data["status"] == 500) {
// TODO: error message and handling here
console.log(data);
}
return data["status"];
});
}
后端代码(app.js):
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'authorization,Content-Type, X-Requested-With');
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.use('/api', api);
还为 app.js 尝试了此配置:
function setupCORS(req, res, next) {
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'authorization,Content-Type');
res.header('Access-Control-Allow-Origin', '*');
console.log("METHOD: " + req.method);
if (req.method === 'OPTIONS') {
console.log('OPTIONS >>>');
res.status(200).end();
} else {
console.log('NOT OPTIONS >>>');
next();
}
}
app.all('/*', setupCORS);
后端代码(api.js):
router.post('/deletePost', function (req, res, next) {
console.log('here here'); // does not print to console
// other code here
}
router.post('/updatePost', function (req, res, next) {
console.log('here here'); // prints just fine
// other code here
}
【问题讨论】: