【问题标题】:XMLHttpRequest error when updating document, but CORS should be enabled更新文档时出现 XMLHttpRequest 错误,但应启用 CORS
【发布时间】: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


【解决方案1】:

你可以使用cors node 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'})
});

【讨论】:

  • 我已经将第二行设为“const app = express();”另外两条线没有任何改变,是的,cors 已安装。
  • 您还需要将 cors 添加到处理程序。我更新我的答案
  • 仅在将 CORS 应用于一个路由时才需要处理程序。 “app.use(cors());”应该全局处理它,但它没有
猜你喜欢
  • 2017-04-29
  • 1970-01-01
  • 2017-11-21
  • 2020-01-01
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
相关资源
最近更新 更多