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.

2 Answers 2

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 ) 
Sign up to request clarification or add additional context in comments.

Comments

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)

2 Comments

i tried "content-type":"multipart/form-data" didnt work
@EaGLE – Putting a claim that you are sending multipart/form-data in the headers will not change the format of the data you are sending.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.