229

I am trying to post on an API with some query params. This is working on PostMan / Insomnia when I am trying to by passing mail and firstname as query parameters :

 http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName 

However, when I am trying to do it with my react native app, I got a 400 error (Invalid Query Parameters).

This is the post method :

.post(`/mails/users/sendVerificationMail`, { mail, firstname }) .then(response => response.status) .catch(err => console.warn(err)); 

(my mail and firstname are console.logged as follow: [email protected] and myFirstName).

So I don't know how to pass Query Parameters with Axios in my request (because right now, it's passing data: { mail: "[email protected]", firstname: "myFirstName" }.

4 Answers 4

428

axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:

.post(`/mails/users/sendVerificationMail`, null, { params: { mail, firstname }}) .then(response => response.status) .catch(err => console.warn(err)); 

This will POST an empty body with the two query params:

POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

Sign up to request clarification or add additional context in comments.

1 Comment

This was quite a gotcha. For example curl is happy with query string params in the URL when doing a post: curl -X POST -H "token: 692792" -d '{"message": "xxxxxx"}' blahblah.com/?param1=apple
35

As of 2021 insted of null i had to add {} in order to make it work!

axios.post( url, {}, { params: { key, checksum } } ) .then(response => { return success(response); }) .catch(error => { return fail(error); }); 

1 Comment

Year makes no sense. For axios version 0.27.2, null or undefined works as the second parameter. axios.post(url, null, { params: { ... } })
13

In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.

 var data = {}; const params = new URLSearchParams({ contact: this.ContactPerson, phoneNumber: this.PhoneNumber, email: this.Email }).toString(); const url = "https://test.com/api/UpdateProfile?" + params; axios .post(url, data, { headers: { aaid: this.ID, token: this.Token } }) .then(res => { this.Info = JSON.parse(res.data); }) .catch(err => { console.log(err); }); 

Comments

3

You can use params and body together in a request with axios

 sendAllData (data) { return axios .post(API_URL + "receiveData", JSON.stringify(data), { headers: { "Content-Type": "application/json; charset=UTF-8" }, params: { mail: [email protected] }, //Add mail as a param }) .then((response) => console.log("repsonse", response.status)); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.