更新文档时出现XMLHttpRequest错误,但应启用CORS

时间:2018-11-19 13:49:28

标签: node.js angular express mongoose

当我尝试更新记录时,出现以下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错误,需要进行修复才能真正进行更新。

1 个答案:

答案 0 :(得分:0)

您可以使用cors节点js库(https://www.npmjs.com/package/cors):

var cors = require('cors');
var app = express();
app.use(cors());

将cors添加到处理程序中:

app.get('/products/:id', cors(), function (req, res, next) {
    res.json({msg: 'This is CORS-enabled'})
});