0

I have a scipt tag in which im making a post request to a route through axios.Axios is not sending the parameters through. Here is the code for axios:

 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script type="text/javascript">

const data={'firstName':"sai"}

    axios({
      url: "/",
      method: "post",
      data: data,
    })
    .then(response => {
      console.log(response);
    })
    .catch(error => console.error(error));
  </script>

Here is the express side of things:

app.post("/",function(req,res){
   console.log("post route");
    console.log(req.body);
})

Im console.logging the data coming from the post request with the help of req.body(I also have body-parser working just fine.Tested with other normal forms).The req comes through to hit the post route.BUt the body is empty always logs "{}". Please help me out with this.

Sai Darshan
  • 252
  • 3
  • 13

2 Answers2

2

Option 1: Define config object

let config = {
  headers: {
     'Content-Type': 'application/x-www-form-urlencoded',
  } 
}  

Mandatory: Use array for params and not js object for 'application/x-www-form-urlencoded'

const params = new URLSearchParams();
params.append('PARAM1', 'VALUE1');
params.append('PARAM2', 'VALUE2');

Call post

 axios.post( uri, params, config )

or

 axios({
     url,
     headers: { 'content-type': 'application/x-www-form-urlencoded' }
     data: params
 })

Option 2: Create an api instance (optional) and set default content-type

const api_local = axios.create({
   baseURL: 'http://localhost:1000/myapi',
});
api_local.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 

Mandatory: Use array for params and not js object for 'application/x-www-form-urlencoded'

const params = new URLSearchParams();
params.append('PARAM1', 'VALUE1');
params.append('PARAM2', 'VALUE2');

Call post

 api_local.post( uri, params )
Benpaper
  • 144
  • 4
1

I also have body-parser working just fine.Tested with other normal forms

Normal forms submit data encoded as either multipart/form-data or application/x-www-form-urlencoded.

Axios submits data, by default, as application/json.

You need a different body parser. One which supports JSON.

(Or to submit the data in a different format)

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335