【发布时间】:2019-04-21 21:31:18
【问题描述】:
当我尝试更新记录时,出现以下 CORS 错误:
Cross origin requests are only supported for HTTP.
XMLHttpRequest cannot load localhost:3000/api/adverts/5bf2b76c38c88dd144e5d4c3 due to access control checks.
在 create.component.ts 中:
onSaveAdvert(form: NgForm){
if (form.invalid) {
console.log("fail");
return;
}
console.log(form.value.title);
this.advertService.updateAdvert(this.id, form.value.title, form.value.content, form.value.make, form.value.model, form.value.color, form.value.price, form.value.milage, form.value.doors, form.value.year, null);
console.log("succes");
form.resetForm();
}
advert.service.ts 中的更新函数:
updateAdvert(id: string, title: string, content: string, make: string, model: string, color: string, price: number, milage: number, doors: number, year: number, addedOn: any){
const advert: Advert = {_id: id, title: title, content: content, make: make, model: model, color: color, price: price, milage: milage, doors: doors, year: year, addedOn: null};
this.http.put("localhost:3000/api/adverts/" + id, advert)
.subscribe(response => console.log(response));
}
app.js 中的 Express 端点:
app.put("/api/adverts/:id", (req, res, next)=>{
const advert = new Advert({
_id: req.body.id,
title: req.body.title,
content: req.body.content,
make: req.body.make,
model: req.body.model,
color: req.body.color,
price: req.body.price,
milage: req.body.milage,
doors: req.body.doors,
year: req.body.year
})
Advert.updateOne({_id: req.params.id}, advert).then(result => {
console.log(result);
res.status(200).json({message: "succesful"});
});
});
在 app.js 中设置标头:
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
好像是CORS问题,但是我可以GET、POST和DELETE数据库中的记录,但是更新会抛出这些错误。
更新: 我换了:
this.http.put("localhost:3000/api/adverts/" + id, advert)
与:
this.http.put(`${this.uri}/api/adverts/${id}`, advert)
在 advert.service.ts 中的 updateAdvert() 中。
控制台现在在客户端中没有显示任何内容,但我收到了一个 mongoDB 错误,我需要在更新实际发生之前修复该错误。
【问题讨论】:
-
更新会抛出这些错误 - 请告诉我们更新请求是什么样的(它使用什么http方法,标题,正文;相关的js在advert.service.ts 中的更新函数,对吧?)。基本上,这听起来像是 GET、POST 和 DELETE 工作,但 PUT 没有,对吧?
-
我记录了整个 req 对象,发现:body: { price: 54325432, milage: 5432543, title: 'KAAS', content: 'test, make: 'test', model: 'test ',颜色:'test',门:'1',年份:'1'},_body:true,长度:未定义,路由:Route { path:'/api/adverts/:id',堆栈:[Layer { 键:[],正则表达式:{ /^\/?$/i fast_star: false, fast_slash: false }, method: 'put' } ], methods: { put: true } } }
-
我也发现了这个错误,我现在要解决这个问题。 (node:54147) UnhandledPromiseRejectionWarning: MongoError: Performing an update on the path '_id' would modify the immutable field '_id' Not sure if it is related
-
您的问题解决了吗?
标签: node.js angular express mongoose