【问题标题】:React + .NET Core Web API, Failed to fetchReact + .NET Core Web API,无法获取
【发布时间】:2021-12-16 04:12:10
【问题描述】:

我正在尝试使用 React 进行登录、注册页面,并且我正在使用 JWT 进行身份验证。 我的后端工作正常,我在 Postman 上对其进行了测试,并且可以正常工作。

但是当我开始构建前端时,我遇到了错误。

我的代码是:

 import { METHODS } from "http";
 import React, { SyntheticEvent, useState } from "react";
 const Register = () => {
 const [FirstName,setName ] = useState('');
 const [LastName,setLastName ] = useState('');
 const [Email,setEmail ] = useState('');
 const [Password,setPassword ] = useState('');
 const submit  = async (e:SyntheticEvent) => {
 e.preventDefault();

 const response = await fetch ('http://localhost:44385/api/auth/register' , {
 method:'POST',
 headers: {'Content-Type' : 'application/json'},
 body: JSON.stringify( {
    FirstName,
    LastName,
    Email,
    Password
  })
})
 const content = await response.json();
console.log(content);

}
return (
<form onSubmit={submit}>

<h1 className="h3 mb-3 fw-normal">Register</h1>

<input  className="form-control"  placeholder="FirstName" required
onChange={e=> setName(e.target.value)} />

<input  className="form-control"  placeholder="Last Name" required
onChange={e=> setLastName(e.target.value)} />

<input type="email" className="form-control"  
  placeholder="name@example.com" required 
 onChange={e=> setEmail(e.target.value)}/>

<input type="password" className="form-control"  placeholder="******" 
  required 
onChange={e=>setPassword(e.target.value)}/>

 <button className="w-100 btn btn-lg btn-primary" 
   type="submit">Submit</button>
 </form>
);
};

 export default Register;

错误:

【问题讨论】:

    标签: reactjs asp.net-core-webapi


    【解决方案1】:

    尝试添加:

     "proxy": "http://localhost:44385",
    

    到你的 React 项目的 package.json

    我还建议将您的 fetch 包含在 try/catch 块中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-10
      • 2018-05-10
      • 2021-11-08
      • 2021-10-24
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多