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

时间:2019-04-11 11:07:32

标签: 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);
    });
}

但是当我进入“网络”标签时,与请求一起发送的数据似乎在有效载荷中。

enter image description here

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

2 个答案:

答案 0 :(得分:0)

如果要在有效负载中将数据作为表单数据而不是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);
  });
};

答案 1 :(得分:0)

您可以在axios中使用FormData()之类的方法来

var body = new FormData();
body.set('userName', 'test');
body.set('password', 'test');
body.set('user_type', 1);

然后您可以使用axios post方法(可以相应地对其进行修改)

axios({
    method: 'post',
    url: 'http://demo.com/api/v1/end-user/login',
    data: body,
    config: { headers: {'Content-Type': 'multipart/form-data' }}
    })
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });
相关问题