小编典典

未在axios请求中发送主体数据

reactjs

我正在尝试通过axios请求将数据发送到我的后端脚本,但是主体看起来是空的。

这是前端发送的请求:

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);

})

但是我的{}身体变得空虚。我正在获取标头和其他数据,但没有数据。


阅读 219

收藏
2020-07-22

共1个答案

小编典典

GET请求不应包含主体。

将方法从“ GET”更改为“ POST”

像这样:

axios.request({
  method: 'POST',
  url: `http://localhost:4444/next/api`,
  headers: {
    'Authorization': token
  },
  data: {
    next_swastik: 'lets add something here'
  },

})

并更改您的api以期待发布

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以注销参数

app.get('/next/api', verifyToken, function(req, res) {
console.log(req.params);
});

就像@MaieonBrix所说的那样,请确保标头包含要发送的内容类型。

2020-07-22