Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

javascript - body data not sent in axios request

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

Here's a back-end:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

GET requests should not have a body.

Change the method from 'GET' to 'POST'

Like so:

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

})

and change your api to expect a post

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

or

Change the data property to params

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

})

and change the api to log out the params

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

and like @MaieonBrix said, make sure that your headers contain the content type that you are sending.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...