TypeError:无法在reactjs登录页面中获取

Posted

技术标签:

【中文标题】TypeError:无法在reactjs登录页面中获取【英文标题】:TypeError: Failed to fetch in reactjs login page 【发布时间】:2020-04-01 10:02:22 【问题描述】:

我一直在尝试创建一个登录页面,但我收到了这个名为 "TypeError: Failed to fetch" 的错误。我不知道我在哪里做错了,我检查了一些 *** 答案,就像我在 *** 答案之一中看到的那样尝试添加event.preventdefault,但这并没有帮助。

有人可以指出我做错的部分吗?

另请注意:使用 API 在邮递员中运行良好。我在那里尝试了相同的电子邮件和密码,它在邮递员中工作正常,但反应网站出现错误。

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"

如果我删除引号,那么它会给我邮递员错误的字符串错误 但在代码沙箱中,当我保存沙箱时,引号会自动删除。可能是因为这个还是没什么好担心的?

【问题讨论】:

您是否在控制台中收到更多错误消息或任何状态代码?该问题可以是CORS 问题。 不,只是 typeError: Failed to fetch. 【参考方案1】:

首先,您需要提供输入名称属性,以便能够正确更新状态 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 应用程序中的这些修复是不够的,因为 codeandbox 使用 https 而 login api 使用 http。这将给出以下错误:

混合内容:“https://hkj22.csb.app/Login”处的页面已加载 通过 HTTPS,但请求了不安全的资源 'http://***/api/authenticate'。该请求已 受阻;内容必须通过 HTTPS 提供。

解决此问题的唯一方法似乎是使用 https 作为该 answer 中所述的 api。

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

【讨论】:

我仍然收到同样的错误 TypeError: Failed to fetch with your updated code。 @UbuntuNewb 那么你还有 cors 问题。在您的 api 中启用 cors 后,此代码将起作用。 @UbuntuNewb 你在你的 api 中启用了 cors 吗? 我不做后端。这项工作有一个后端人员。在将问题转给他之前,我怎么知道存在 cors 问题? @UbuntuNewb 如果出现任何错误,请检查您的浏览器控制台。

以上是关于TypeError:无法在reactjs登录页面中获取的主要内容,如果未能解决你的问题,请参考以下文章

TypeError:无法读取reactjs中未定义的属性“长度”

ReactJS:TypeError:无法读取未定义的属性“纬度”

REACT JS:TypeError:无法读取未定义的属性“参数”

React Js:在页面手动刷新之前无法登录

ReactJS:TypeError:无法添加/删除密封数组元素

ReactJS TypeError:无法读取未定义的属性(读取'main')