簡體   English   中英

類型錯誤:無法在 reactjs 登錄頁面中獲取

[英]TypeError: Failed to fetch in reactjs login page

我一直在嘗試創建一個登錄頁面,但我收到了一個名為"TypeError: Failed to fetch" 我不知道我哪里做錯了,我檢查了一些 StackOverflow 的答案,就像我在 StackOverflow 的一個答案中看到的那樣嘗試添加event.preventdefault ,但這沒有幫助。

有人可以指出我做錯的部分嗎?

另請注意:它在郵遞員中使用 API 工作正常。 我在那里嘗試了相同的電子郵件和密碼,它在郵遞員中工作正常,但在 react 網站上出現錯誤。

import React, { Component } from "react";
class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: ""
    };
    this.onchange = this.onchange.bind(this);
  }

  onchange(e) {
    this.setState({ [e.target.name]: e.target.value });
    console.log(this.state);
  }

  performLogin = async event => {
    event.preventDefault();
    console.log("button clicked");
    var body = {
      password: "this.state.password",
      email: "this.state.email"
    };

    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify(body)
    };

    const url = "/api/authenticate";

    try {
      const response = await fetch(url, options);
      const result = await response.json();
      console.log(result);
      console.log(`login successful`);
      window.alert("login succesful");
    } catch (error) {
      console.error(error);
    }
  };

  render() {
    return (
      <div>
        <input type="text" placeholder="emailid" onChange={this.onchange} />
        <br />
        <input
          type="password"
          placeholder="Enter your Password"
          onChange={this.onchange}
        />
        <br />
        <button type="submit" onClick={event => this.performLogin(event)}>
          Submit
        </button>
      </div>
    );
  }
}
export default Login;

一個異常是在郵遞員中,只有當我像下面顯示的那樣發帖時它才接受

{
    "password":"pass",
    "email":"admin"
}

如果我刪除引號,那么它會在郵遞員中出現錯誤的字符串錯誤,但在代碼沙箱中,當我保存沙箱時,引號會自動刪除。 可能是因為那個還是沒什么可擔心的?

首先,您需要提供輸入名稱屬性,以便能夠像這樣正確更新狀態 onChange:

<input type="text" name="email" placeholder="emailid" onChange={this.onchange} /> <br />
<input type="password" name="password" placeholder="Enter your Password" onChange={this.onchange}/>

其次,您需要像這樣創建請求正文:

   var body = {
      password: this.state.password,
      email: this.state.email
    };

最后,您需要檢查 fetch 響應是否正常,因為在 4xx 錯誤中 fetch 不會給出錯誤。

因此,有了所有這些更改,您的組件代碼必須是這樣的:

import React, { Component } from "react";
class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: ""
    };
    this.onchange = this.onchange.bind(this);
  }
  onchange(e) {
    this.setState({ [e.target.name]: e.target.value });
  }
  performLogin = async event => {
    event.preventDefault();
    var body = {
      password: this.state.password,
      email: this.state.email
    };
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify(body)
    };
    const url = "/api/authenticate";
    try {
      const response = await fetch(url, options);
      const result = await response.json();
      console.log(result);
      if (response.ok) {
        console.log("login successful");
        window.alert("login succesful");
      } else {
        console.log("login failed");
        window.alert("login failed");
      }
    } catch (error) {
      console.error(error);
    }
  };

  render() {
    return (
      <div>
        <input
          type="text"
          name="email"
          placeholder="emailid"
          onChange={this.onchange}
        />
        <br />
        <input
          type="password"
          name="password"
          placeholder="Enter your Password"
          onChange={this.onchange}
        />
        <br />
        <button type="submit" onClick={event => this.performLogin(event)}>
          Submit
        </button>
        <hr />
        State: {JSON.stringify(this.state)}
      </div>
    );
  }
}
export default Login;

但是react app 中的這些修復是不夠的,因為codeandbox 使用https 而login api 使用http。 這將給出以下錯誤:

混合內容:“ https://hkj22.csb.app/Login ”頁面已通過 HTTPS 加載,但請求了不安全的資源“http://***/api/authenticate”。 此請求已被阻止; 內容必須通過 HTTPS 提供。

解決此問題的唯一方法似乎是使用 https 用於 api,如本答案所述

您可以聯系 api 所有者使用 https 托管他的 api。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM