axios 将数据作为表单数据发布,而不是作为有效负载中的 JSON

Par*_*ale 5 reactjs axios

我只是在尝试我的第一个 reactJS 应用程序。

因为我使用 axios.post() 方法发送数据。

submitHandler = event => {
  event.preventDefault();
  axios
    .post("http://demo.com/api/v1/end-user/login", {
      username: "",
      password: "",
      user_type: 1
    })
    .then(res => {
      console.log(res);
      console.log(res.data);
    });
}
Run Code Online (Sandbox Code Playgroud)

但是当我检查我的网络选项卡时,我与请求一起发送的数据似乎在有效载荷中。

在此处输入图片说明

我想将数据作为表单数据发送。我错过了什么吗?

Tho*_*lle 7

如果您想将数据作为表单数据而不是负载中的 JSON 发送,您可以创建一个FormData对象并将其用作第二个参数。

submitHandler = event => {
  event.preventDefault();

  const formData = new FormData();
  formData.append("username", "");
  formData.append("password", "");
  formData.append("user_type", 1);

  axios.post("http://demo.com/api/v1/end-user/login", formData).then(res => {
    console.log(res);
    console.log(res.data);
  });
};
Run Code Online (Sandbox Code Playgroud)