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

Gui*_*eRZ 21 javascript mysql post axios

我试图在API上发布一些查询参数.当我尝试将mail和firstname作为查询参数传递时,这正在处理PostMan/Insomnia:

 http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用我的本机应用程序时,我收到400错误(无效的查询参数).

这是post方法:

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

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

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

谢谢您的帮助.

ena*_*upe 54

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

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

这将使用两个查询参数POST一个空体:

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

  • @khodekazemi .post(`/mails/users/sendVerificationMail`, body, { params: { mail, firstname }}) .then(response => response.status) .catch(err => console.warn(err)); (3认同)
  • @Thomas你为什么这么说以及为什么这与这个问题相关? (2认同)

Jay*_*Pow 12

就我而言,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);
          });
Run Code Online (Sandbox Code Playgroud)


小智 8

到 2021 年插入 null 时,我必须添加 {} 才能使其工作!

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

  • 年份没有意义。对于“axios”版本“0.27.2”,“null”或“undefined”用作第二个参数。`axios.post(url, null, { params: { ... } })` (3认同)