简体   繁体   English

使用参数MongoDB NodeJS删除请求

[英]Delete Request with params MongoDB NodeJS

I try to send delete request from Angular 4 to mongoDb 我尝试将删除请求从Angular 4发送到mongoDb

I have an array of ids, which I want to delete and in my service I have a function 我有一个ID数组,我想删除它,在我的服务中我有一个函数

  deleteData(id) {
    return this.http.delete( this.api, id)
  }

Then in my component I build an array of objects (because I need to pass it to backend as JSON - as an array it won't be probably recognised) 然后在我的组件中构建一个对象数组(因为我需要将其作为JSON传递给后端-作为数组,可能无法识别它)

  deleteData(data) {
    const dataToSend = [];
    let oneDataToSend;

    for (let i = 0; i < data.length; i++) {
      oneDataToSend = {'_id': ''};
      oneDataToSend._id = data[i];
      dataToSend.push(oneDataToSend);
    }
    this.service.deleteData(dataToSend).subscribe((res) => {
      console.log(data);
    });
  }

And after that I try to delete objects, which ids are the same as in a query 然后,我尝试删除对象,这些ID与查询中的ID相同

app.delete('/tasks', function(req,res){
  console.log(req.body);
  var ids = [];
  for (let i = 0; i < req.body.length; i ++) {
    ids.push(req.body[i]._id);
  }
  var myquery = { _id: { $in: ids } };
  Model.collection.deleteMany(myquery, function(err, obj) {
    if (err) throw err;
  });
});

Here I got the problem, that there req.body is empty {} Also, in console in Network section I see 2 requests OPTIONS (with Status Code 204 No Content) DELETE without any info 在这里,我遇到了一个问题,即req.body为空{}此外,在网络部分的控制台中,我看到2个请求选项(状态代码为204,无内容),删除时没有任何信息

Could you please give me a hint and help to solve this problem? 您能给我一个提示并帮助解决这个问题吗?

The reason you see the OPTIONS request with a 204 NO CONTENT response is because of Cross Origin Resource Sharing (CORS). 您看到带有204 NO CONTENT响应的OPTIONS请求的原因是由于跨源资源共享 (CORS)。 The client is checking if it is allowed to make a DELETE request to your backend. 客户端正在检查是否允许向您的后端发出DELETE请求。

Consider allowing CORS in the backend application. 考虑在后端应用程序中允许CORS。 For an easy way for express, use expressjs/cors . 为了方便表达,请使用expressjs / cors However, make sure you understand the security implications of allowing cross-site requests. 但是,请确保您了解允许跨站点请求的安全隐患。

Also, are you parsing the request body? 另外,您是否在解析请求正文? If not, it will be undefined in req.body. 如果没有,它将在req.body中未定义。

You can use express.json() , it will attempt to parse the JSON of the request body and save it to req.body, but only if the header "Content-Type: application/json" is sent along with the request: 您可以使用express.json() ,它将尝试解析请求正文的JSON并将其保存到req.body,但前提是必须将标题“ Content-Type:application / json”与请求一起发送:

const app = express();
app.use(express.json()); // Parses request body if type is json. Saves to req.body.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM