本文介绍了正文数据未在 axios 请求中发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过 axios 请求将数据发送到我的后端脚本,但正文看起来是空的.
I am trying to send data through axios request to my backend script, but the body looks empty.
这是从前端发送的请求:
Here's a request sent from front-end:
axios.request({
method: 'GET',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
data: {
next_swastik: 'lets add something here'
},
}).then((res)=>{
console.log("api call sucessfull",res);
}).catch((err)=>{
console.log("api call unsucessfull",err);
this.props.toggleLoading(false);
})
这是一个后端:
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.body);
})
但我得到 {}
空体.我正在获取标题和其他数据,但不是数据.
But I am getting {}
empty body. I am getting headers and other data but not data.
推荐答案
GET 请求不应有正文.
GET requests should not have a body.
将方法从GET"更改为POST"
Change the method from 'GET' to 'POST'
像这样:
axios.request({
method: 'POST',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
data: {
next_swastik: 'lets add something here'
},
})
并更改您的 api 以期待发布
and change your api to expect a post
app.post('/next/api', verifyToken, function(req, res) {
console.log(req.body);
});
或
将 data
属性更改为 params
axios.request({
method: 'GET',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
params: {
next_swastik: 'lets add something here'
},
})
并更改api以注销参数
and change the api to log out the params
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.params);
});
就像@MaieonBrix 所说的,确保您的标头包含您要发送的内容类型.
and like @MaieonBrix said, make sure that your headers contain the content type that you are sending.
这篇关于正文数据未在 axios 请求中发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!