【问题标题】:How to add id and body to axios.PUT request?如何将 id 和 body 添加到 axios.PUT 请求?
【发布时间】:2018-02-09 17:34:34
【问题描述】:

我正在使用带有 REACT 的 axios,并且想知道如何使用它来发出 put 请求,以通过我设置的后端节点/express API 更新对象。

我需要能够传递idbody,但不知道如何传递。

axios.put('/api/profile', id, body)
.then(response => { 

console.log(response.data);
})
.catch(err => { 

console.log(err);
});

我认为这不会起作用,因为它需要 put(url, data, {headers}) 的参数

【问题讨论】:

  • id 是路由参数吗?这意味着实际解析的 url 是 /api/profile/:id 还是它的一部分?
  • 我没有将它作为路由参数,但我想我可以将它添加到后端。这会是这样做的最佳方式吗?
  • 这是一种常见的做法。所以你会 sd 类似axios.put('/api/profile' + id, body) then on your server you can define your route this way: app.post('/api/profile/:id')`,然后 id 将在 req.params.id 中可用
  • 不把它放在路由参数中的另一种方法是什么?
  • 你可以把它放在一个查询字符串中,但这有点奇怪

标签: node.js reactjs express axios


【解决方案1】:

此模式是使用您要更新的实体/项目的 id 发出 axios 请求并返回,如下所示:

    axios.put(`/api/profile/${id}`, body); //using string interpolation
    axios.put('/api/profile' + id, body); //using string concatenation

然后,在您的 express/node 后端,您将拥有一个与此请求的 URI 路径匹配的路由,并使用正文更新该配置文件。不确定您的数据库使用的是什么,但在伪代码中它看起来像这样:


    /* 
     * 1. query profile Model for the specific profile
     * 2. make sure to check if foundProfile is undefined or not.
     * 3. update profile with body
     * 4. Catch on errors
     */
    router.put('/api/profile/:id', (req, res, next) => {
        Profile.findbyId(req.params.id)
           .then(foundProfile => foundProfile.update(req.body))  
           .catch(next);
    })

正如上面评论中提到的,您可以通过查询字符串执行此操作,但这会是奇怪/反模式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 2015-11-16
    • 2018-08-09
    • 1970-01-01
    • 2011-10-14
    • 2021-03-30
    • 2011-12-11
    相关资源
    最近更新 更多