Axios PUT不会更新数据

时间:2018-11-22 22:12:07

标签: node.js rest express vue.js axios

我有这个VueJS应用程序,该应用程序正在使用Axios PUT服务器对象。目标是更新数据库中的该对象。该对象已经存在于数据库中,但是用PUT发送回的对象具有一些已更改的数据。这些更改是我要更新到数据库的内容。该应用程序运行时没有错误消息,但是数据库中的数据从未更新。

  

客户端

onUpload(): void {
    this.chosenRoute.name = this.routeName;
    this.chosenRoute.text.paragraphs[0] = this.routeDescription;
    this.chosenRoute.text.preamble = this.preamble;
    if(this.activity != "") this.chosenRoute.activity = this.activity;

    axios.put('http://localhost:8080/route/' + this.selectedRoute, JSON.stringify(this.chosenRoute), {
      onUploadProgress: uploadEvent => {
        console.log('Upload Progress' + Math.round(uploadEvent.loaded / uploadEvent.total) * 100 + " %");
      }
    }).then(res => {
      console.log(res);
    });
  }
  

服务器端

app.put('/route/:id', function(req, res, next) {
    const routeId = req.params.id;
    res.set("Access-Control-Allow-Origin", "*");
    Route.update({'_id':routeId}, req.body, function(result) {
        return res.send(result);
    });
});

1 个答案:

答案 0 :(得分:1)

我认为您不应该使用JSON.stringify,因此您的代码应类似于:

axios.put(`http://localhost:8080/route/${this.selectedRoute}`, this.chosenRoute, {
  onUploadProgress: uploadEvent => {
    console.log('Upload Progress' + Math.round(uploadEvent.loaded / uploadEvent.total) * 100 + " %");
  }
}).then(res => {
  console.log(res);
});

希望它将对您有帮助!