如何使用 Axios 发布查询参数?

2021-12-18 00:00:00 axios post javascript mysql

我正在尝试使用一些查询参数在 API 上发帖.当我尝试通过将邮件和名字作为查询参数传递时,这适用于 PostMan/Insomnia :

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

但是,当我尝试使用 React Native 应用程序执行此操作时,出现 400 错误(查询参数无效).

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

这是post方法:

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

(我的邮件和名字在控制台中记录如下:lol@lol.commyFirstName).

(my mail and firstname are console.logged as follow: lol@lol.com and myFirstName).

所以我不知道如何在我的请求中使用 Axios 传递查询参数(因为现在,它正在传递 data: { mail: "lol@lol.com", firstname: "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" }.

推荐答案

axios 签名为 axios.post(url[, data[, config]]).所以你想在第三个参数中发送 params 对象:

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:

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

相关文章