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

时间:2018-11-27 13:48:21

标签: javascript mysql post axios

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

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

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

这是发布方法:

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

(我的邮件和名字是console.log,记录如下:lol@lol.commyFirstName)。

因此,我不知道如何在请求中通过Axios传递查询参数(因为现在,它正在传递data: { mail: "lol@lol.com", firstname: "myFirstName" }

谢谢您的帮助。

4 个答案:

答案 0 :(得分:24)

帖子的

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

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

这将发布带有两个查询参数的空正文:

  

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

答案 1 :(得分:7)

从 2021 年开始,我必须添加 {} 才能使其工作!

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

答案 2 :(得分:3)

就我而言,该API的响应为CORS错误。我改为将查询参数格式化为查询字符串。它成功发布了数据,并且避免了CORS问题。

        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);
          });

答案 3 :(得分:-3)

尝试直接传递到您的URL

示例

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

或作为post()

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