Angular 2:预检响应中的Access-Control-Allow-Methods不允许方法DELETE

时间:2017-02-14 04:43:55

标签: mongodb angular express mongoose

我需要使用mongoose删除我的mongodb上的记录。

这是我的组件

 deleteProduct(product){
        this._confirmationService.confirm({
            message: 'Are you sure you want to delete the item?',
            accept: () => {
                this._productsAdminService.deleteProduct(product._id)
                    .subscribe(products => {
                        products.forEach(function(product){
                            if(product.cat_id === 1) product.catName = 'Dota Shirts';
                            if(product.cat_id === 2) product.catName = 'Gym Shirts';
                            if(product.cat_id === 3) product.catName = 'Car Shirts';
                        });
                        this.products = products;
                    },
                    err => console.log(err));
            }
        })
    }

基本上这只会将产品ID传递给服务以执行http请求。

这是我的服务

deleteProduct(productId){
    let headers = new Headers({'Authorization': 'JWT ' + localStorage.getItem('currentUserToken')});
    let options = new RequestOptions({ headers: headers});
    return this._http.delete('http://localhost:3000/admin/products/delete/' + productId, options)
        .map((response: Response) => response.json())
        .catch(this._handlerError);
}

我正在使用delete方法在expressJS中调用我的API。

这是我的API

productsAdminRouter.route('/delete/:productId')
    .delete(function(req,res){
        id = req.params.productId;
        console.log(id);
        Products.findByIdAndRemove(id)
            .exec(function(err, done){
                if (err) throw err;
                Products.find()
                    .exec(function(err, products){
                        res.json(products);
                    });
            });
    });

但我总是遇到这个错误

enter image description here

有人可以帮忙吗?我被卡住了。

2 个答案:

答案 0 :(得分:0)

我在使用Java-Spring后端时遇到了同样的问题:当发生跨源资源共享(或简称cors)时,Angular会发送pre-flight请求之前实际(此处为DELETE )请求,其类型为OPTIONS(http)。

你要做的是:

  • 在您的服务器上启用CORS
  • 确保您的服务器接受该特定端点(/delete/:productId
  • 上的OPTIONS请求
  • Access-Control-Allow-Methods标题添加到OPTIONS,DELETE
  • 的响应中

答案 1 :(得分:0)

正如@flashjpr所说

我必须为我的实体写一个特定的中间件" ticket"。

var allowDelete = function(req, res, next){
  res.append('Access-Control-Allow-Methods', 'DELETE')
  next()
}

并将其传递给该实体的第一个中间件

app.use('/tickets', allowDelete, tickets);

编辑:我正在使用expressjs