使用axios实现DELETE请求的最简单方法是什么?

时间:2018-03-06 10:21:20

标签: node.js vue.js vuejs2 axios http-delete

我试图弄清楚如何解决以下错误是不成功的,(第一个错误:)'OPTIONS http://localhost:3000/lists/5a9dca48cebb5a4e5fc1bfe9 404(Not Found)'和(第二个错误:)'无法加载{{3 :预检的响应包含无效的HTTP状态代码404.'。

最初,我的代码与以下相同:http://localhost:3000/lists/5a9dca48cebb5a4e5fc1bfe9

看过很多与我的问题相似的帖子,但他们建议的解决方案都没有对我有用。

我在后面使用Vue.js,Axios和Node.js,我的集合在MongoDb中定义如下:

   List: {_id:'', name:'', items:
                [ {
                    title: '',
                    category: ''            
                  }
                ]
           }

GetList.vue:

methods: {
  fetchLists(){
    let uri = 'http://localhost:3000/lists';
    axios.get(uri).then((response) => {
                  this.List = response.data;
                  console.log(this.List[3].items[0]);
                  console.log(this.List);
              });
  },

  DELETE(a_list, id){
    $("#myModal").modal('show');
    this.list = a_list;
    this._id = id;
  },
  deleteList : function(_id){
    // let uri = 'http://localhost:3000/lists/'+_id;
    // this.List.splice(_id, 1);
    axios.delete('http://localhost:3000/lists/'+_id)
    .then((response) => {
      this.fetchLists();
      //refreshes Application
      // window.location.reload();
    })
    .catch((error) => {
      console.log(error);
    });


  }

ListController:

exports.delete_a_list = function(req, res)=>{
console.log(req.params);
List.deleteOne({req.params.listId}, function(err, list){
    if(err){res.json(err);};
    else
    {res.json({list: 'List successfully deleted'});}
  };
});

更新:

运行'npm install cors --save'后,它存储在我的package.json中。 服务器/的package.json:

{
  "name": "api",
  "version": "1.0.0",
  "description": ":)",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "keywords": [
    ":)"
  ],
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^1.17.1"
  },
  "dependencies": {
    "cors": "^2.8.4",
    "express": "^4.16.2",
    "mongoose": "^5.0.8",
    "npm": "^5.7.1"
  }
}

更新:

我也尝试了以下内容:

ObjectID = require('mongodb').ObjectID;

exports.delete_a_list = function(req, res){
    // console.log(req.params);
       List.deleteOne({
        _id: ObjectID(req.params.listId)}, function(err, list){
        if(err)
        res.json(err);
         res.json({list: 'List successfully deleted'});
         });
       };'

返回相同的错误,包括:

  xhr.js?ec6c:178 OPTIONS http://localhost:3000/lists/undefined 404 (Not Found)
dispatchXhrRequest @ xhr.js?ec6c:178
xhrAdapter @ xhr.js?ec6c:12
dispatchRequest @ dispatchRequest.js?c4bb:59
Promise.then (async)
request @ Axios.js?5e65:51
Axios.(anonymous function) @ Axios.js?5e65:61
wrap @ bind.js?24ff:9
deleteList @ GetList.vue?c877:131
boundFn @ vue.esm.js?efeb:190
click @ GetList.vue?d584:124
invoker @ vue.esm.js?efeb:2004
fn._withTask.fn._withTask @ vue.esm.js?efeb:1802
:1 Failed to load http://localhost:3000/lists/undefined: Response for preflight has invalid HTTP status code 404.

 createError.js?16d0:16 Uncaught (in promise) Error: Network Error
   at createError (createError.js?16d0:16)
   at XMLHttpRequest.handleError (xhr.js?ec6c:87)

3 个答案:

答案 0 :(得分:1)

谢谢你们提出的所有建议。

我在网络忍者中找到了以下视频:https://www.youtube.com/watch?v=NEFfbK323Ok,并且在更改我的代码以反映他的特定方法时,能够将最终工作:

listRoutes.js:

app.route('/lists/:_id')
.get(lists.read_a_list)
// .update(lists.update_a_list)
.delete(lists.delete_a_list);

listController.js:

exports.delete_a_list = function(req, res){
// console.log(req.params);
List.findByIdAndRemove({_id: req.params._id}).then(function(list){
    res.send(list);
});

};

GetList.vue:

deleteList : function(_id, List){
axios.delete('http://localhost:3000/lists/'+_id, List)
.then(response => {
  this.List.splice(index, 1);
  //refreshes Application
  // window.location.reload();

  })
}

答案 1 :(得分:0)

您的问题与CORS(跨域资源共享)有关。

如果您使用带有express的节点,那么只需包含此中间件: https://www.npmjs.com/package/cors

答案 2 :(得分:0)

此查询似乎有误:

List.deleteOne({req.params.listId}, ...

你能尝试这样修改吗?:

List.deleteOne({_id: ObjectID(req.params.listId}), ...

(您需要在某处宣布ObjectIDObjectID = require('mongodb').ObjectID

相关问题