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

axios向本地主机发送请求

  •  0
  • Zenryo  · 技术社区  · 4 年前

    我在使用axios向react请求帖子时遇到了一些问题,代码如下

    axios
      .post("http://localhost/priangan/api/user/login", {
        headers: {
          "Content-type": "application/json; charset=UTF-8",
        },
        data: {
          username: this.state.username,
          password: this.state.password,
        },
      }).then((response) => {
        if (response.status == 200) alert("Login Success");
      });
    

    但是当我请求时,控制台中出现了一些错误,如下所示 error in console ,找不到本地主机

    然后我尝试使用fetch,代码如下

    fetch("http://localhost/priangan/api/user/login", {
        method: "POST",
        body: JSON.stringify({
          username: this.state.username,
          password: this.state.password,
        }),
        headers: {
          "Content-type": "application/json; charset=UTF-8",
        },
      }).then((response) => {
        if (response.status == 200) alert("Login Success");
      });
    

    其工作, 那么我在使用axios时有什么问题呢? 谢谢你帮我

    1 回复  |  直到 4 年前
        1
  •  1
  •   ShinaBR2    4 年前

    你没有使用正确的语法。让我们试试这个。

    axios.post(
      "http://localhost/priangan/api/user/login",
      {
        username: this.state.username,
        password: this.state.password,
      },
      {
        headers: {
          "Content-type": "application/json; charset=UTF-8",
        }
      }
    )
    

    所以基本上, axios.post 按顺序接受3个参数:URL、数据和选项。您提供的 data headers 密钥无效。

    正式文件: https://github.com/axios/axios#request-method-aliases