如何将 id 和 body 添加到 axios.PUT 请求?
How to add id and body to axios.PUT request?
我正在将 axios 与 REACT 结合使用,想知道如何使用它发出放置请求以通过我已设置的后端 node/express API 更新对象。
我需要能够通过一个 id
和一个 body
,但不确定如何去做。
axios.put('/api/profile', id, body)
.then(response => {
console.log(response.data);
})
.catch(err => {
console.log(err);
});
我认为这行不通,因为它采用 put(url, data, {headers})
的参数
此模式是使用要更新的 entity/item 和 return 的 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);
})
如上面的评论所述,您可以通过查询字符串执行此操作,但那将是 odd/anti-pattern.
我正在将 axios 与 REACT 结合使用,想知道如何使用它发出放置请求以通过我已设置的后端 node/express API 更新对象。
我需要能够通过一个 id
和一个 body
,但不确定如何去做。
axios.put('/api/profile', id, body)
.then(response => {
console.log(response.data);
})
.catch(err => {
console.log(err);
});
我认为这行不通,因为它采用 put(url, data, {headers})
此模式是使用要更新的 entity/item 和 return 的 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);
})
如上面的评论所述,您可以通过查询字符串执行此操作,但那将是 odd/anti-pattern.