请求失败,状态码为 400,使用 axios

时间:2020-12-30 18:30:52

标签: node.js reactjs axios

我正在尝试使用我使用 node 创建的登录 API,但是,每当我使用 Axios 调用 API 时,它都会在控制台中给我一个请求失败。

这是我使用 axios 调用我的方法的方式:

Density

这是我的登录页面和控制台:

enter image description here

这是我的后端配置:

   axios
      .post(
        "http://localhost:8080/staffMember/login",
        {
          email: "Fred@gmail.com",
          password: "Flintstone",
        },
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      )
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error.message);
      });
  };

1 个答案:

答案 0 :(得分:0)

好吧,我不知道后端是如何配置的,但是您可以从 stringyfing yow body 开始

   axios
      .post(
        "http://localhost:8080/staffMember/login",
        JSON.strinfify({
          email: "Fred@gmail.com",
          password: "Flintstone",
        }),
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      )
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error.message);
      });
  };

如果这没有做任何改变,那么改换标题

   axios
      .post(
        "http://localhost:8080/staffMember/login",
        {
          email: "Fred@gmail.com",
          password: "Flintstone",
        },
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        }
      )
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error.message);
      });
  };

小广告 如果您想通过 axios 结帐 https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a

npm i -S axios-es6-class