未在axios请求中发送主体数据 [英] body data not sent in axios request

查看:152
本文介绍了未在axios请求中发送主体数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to send data through axios request to my backend script, but the body looks empty.

这是前端发送的请求:

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请求中发送主体数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆