【问题标题】:Vue axios delete request not working. How do I fix it?Vue axios 删除请求不起作用。我如何解决它?
【发布时间】:2020-08-24 16:42:54
【问题描述】:

我在删除请求时遇到问题,我的帖子,get 工作正常。 我做错了什么?

 removeUser(id) {
      axios.delete('https://jsonplaceholder.typicode.com/users' + id)
      .then(function(response) {
        const user = response.data;
        this.users.splice(id, user);
      });

【问题讨论】:

  • 试试typicode.com/users/' + id
  • 我也试过了,不行
  • "delete" 方法不返回数据。只是一个空对象。
  • 如何让它返回数据?我的数据中有这个return {users: [],}

标签: vue.js vuejs2 axios


【解决方案1】:

如果response.status === 204,则删除成功。

对于客户端,这里是一个axios的例子,注意users后面有一个'

destroy() {
    return request.delete('/api/users/' + id)
}

对于服务器,这里是一个 Laravel 示例:

if( $article->delete() ) {
    return response()->json(null, 204);
} else {
    abort(409);
}

【讨论】:

    【解决方案2】:

    我在您提供的代码中只能看到 1 个问题。

    您正在尝试通过执行 this.users.splice(id, user); 来修改 Vue 实例 $data users 对象。但是你在回调函数内部,this 不再代表 Vue 实例。 要解决此问题并让users 对象在响应出现后实际修改,您需要这样做:

     removeUser(id) {
      let that = this;
      axios.delete('https://jsonplaceholder.typicode.com/users' + id)
      .then(function(response) {
        const user = response.data;
        that.users.splice(id, user);
      });
    

    现在,我没有来自后端的任何代码,所以我只做一些假设:

    • 路线可能没有很好地定义>如果您使用的是 NodeJS,那么您应该检查您的路线,它应该看起来像这样:

      router.route('/users:id').delete(async function(req,res,next){ /* ... */ });
      
    • 您可能遇到路由问题,因为在用户值之前缺少/

    1 提示:同样,如果您使用的是 NodeJS,您可以在 .delete 路由中使用它:

      res.status(200).json({ errorCode : null , errorMessage : null , users : [] });
    

    查看您是否在前端收到它。

    【讨论】:

      【解决方案3】:

      我认为您确实需要将结尾的“/”附加到 URL,这样 URL 才能正确形成,例如“https://jsonplaceholder.typicode.com/users/123”(而不是“users123”最后)。

      除此之外,Array.prototype.splice 的第一个参数是应该开始删除项目的位置。第二个(可选)参数deleteCount 是要删除的项目数。除了deleteCount,您还可以传递要在start 位置之后以及在删除项目之后插入的对象集合。

      您只需在this.users 数组中找到该对象并将其删除。如果你想使用Array.prototype.splice,那么你可以使用Array.prototype.findIndex在数组中找到用户的索引然后删除它:

      // Find the index of the item to remove
      const indexOfUserToRemove = this.users.findIndex(u => u.id === id);
      
      // Call splice to remove the item
      this.users.splice(indexOfUserToRemove, 1);
      

      【讨论】:

        猜你喜欢
        • 2020-08-14
        • 1970-01-01
        • 2018-11-26
        • 2021-12-07
        • 2018-12-24
        • 2018-05-20
        • 2018-12-25
        • 1970-01-01
        相关资源
        最近更新 更多