代码之家  ›  专栏  ›  技术社区  ›  GuillaumeRZ

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

  •  4
  • GuillaumeRZ  · 技术社区  · 7 年前

    我试图发布一个带有一些查询参数的API。 当我试图通过传递mail和firstname作为查询参数来进行以下操作时,这是对PostMan/失眠的处理:

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

    然而,当我试图用我的react原生应用程序执行此操作时,我得到了一个400错误(无效的查询参数)。

    这是post方法:

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

    lol@lol.com myFirstName

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

    2 回复  |  直到 6 年前
        1
  •  243
  •   enapupe    7 年前

    邮政的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

        2
  •  8
  •   Vasilis Mpletsos    5 年前

    axios.post(
            url,
            {},
            {
              params: {
                key,
                checksum
              }
            }
          )
          .then(response => {
            return success(response);
          })
          .catch(error => {
            return fail(error);
          });
    
        3
  •  3
  •   Gary Bao 鲍昱彤 user17749919    6 年前

    在我的例子中,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);
              });