How to post query parameters with Axios?

我是研究僧i 提交于 2019-11-29 17:01:31

问题


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: lol@lol.com 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: "lol@lol.com", firstname: "myFirstName" }.

Thank you for your help.


回答1:


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




回答2:


Try passing directly to your URL:

Example

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

Or as a third argument to post()

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


来源:https://stackoverflow.com/questions/53501185/how-to-post-query-parameters-with-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!