【发布时间】:2019-07-09 00:05:46
【问题描述】:
所以我有一个小角度应用程序连接到我的节点 api。我的获取请求没有问题,我在加载时从我的 api 获取数据。我的发布请求引发了错误;
从源“http://localhost:4200”对“http://localhost:3000/api/heroes”处的 XMLHttpRequest 的访问已被 CORS 策略阻止:在预检响应中 Access-Control-Allow-Headers 不允许请求标头字段内容类型。
和
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:3000/api/heroes", ok: false, ...}
这是我的post方法@客户端;
addHero(hero: Hero) {
this.http.post<Hero>("http://localhost:3000/api/heroes", hero)
.subscribe((responseData) => {
console.log(responseData);
})
this.heroes.push(hero); //Adds new hero to original array
this.heroesUpdated.next([...this.heroes]); //Adds new array to subject
}
这是我的后端;
app.use((req,res,next) => {
res.setHeader("Access-Control-Allow-Origin", "localhost");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS");
next();
})
app.post("/api/heroes", (req, res,next) => {
const post = req.body;
console.log(post);
res.status(201).json({message:"Succeed"});
});
所以我已经允许 content-type 但我仍然收到错误。有什么建议可以从这里继续吗?
【问题讨论】:
标签: node.js angular cors http-headers