gpt4 book ai didi

reactjs - 类型错误 : "NetworkError when attempting to fetch resource."

转载 作者:行者123 更新时间:2023-12-04 13:21:34 28 4
gpt4 key购买 nike

我发现了很多与我的问题类似的问题,但我没有得到解决方案,这就是我在这里问的原因。

我刚刚开始学习使用 React 进行前端开发。我为在不同端口运行的前端和后端制作了单独的应用程序。

后端:运行于 incomeexpense.stacklearning.com/ 的 Laravel 框架应用程序

前端:React 应用程序运行于 localhost:3000/
我有一个这样的表格:

import React,{Component} from 'react';

export default class Register extends Component{
constructor(props){
super(props);

this.state = {
name: '',
email: '',
password: '',
confirm_password: ''
}
}

updateInput = (event) =>{
const name = event.target.name;
const value = event.target.value;

this.setState({[name]: value});
}

handleSubmit = (event)=>{
event.preventDefault();
fetch('http://incomeexpense.stacklearning.com/api/users', {
method: 'POST',
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
password: this.state.password,
confirm_password: this.state.confirm_password
}),
headers: {
"Content-Type": "application/json",
"Origin": "localhost:3000",
}
}).then(function (response) {
console.log(response);
},function (error) {
console.log(error);
});
}

render(){
return(
<div className="limiter">
<div className="container-login100">
<div className="wrap-login100 p-l-85 p-r-85 p-t-55 p-b-55">
<form className="login100-form validate-form flex-sb flex-w" onSubmit={this.handleSubmit}>
<span className="login100-form-title p-b-32">
Sign Up
</span>
<span className="txt1 p-b-11">
Name
</span>
<div className="wrap-input100 validate-input m-b-36" >
<input className="input100" type="text" name="name" value={this.state.name} onChange={this.updateInput}/>
<span className="focus-input100"></span>
</div>
<span className="txt1 p-b-11">
Email
</span>
<div className="wrap-input100 validate-input m-b-36">
<input className="input100" type="text" name="email" value={this.state.email} onChange={this.updateInput}/>
<span className="focus-input100"></span>
</div>
<span className="txt1 p-b-11">
Password
</span>
<div className="wrap-input100 validate-input m-b-36">
<input className="input100" type="password" name="password" value={this.state.password} onChange={this.updateInput}/>
<span className="focus-input100"></span>
</div>
<span className="txt1 p-b-11">
Confirm Password
</span>
<div className="wrap-input100 validate-input m-b-18">
<input className="input100" type="password" name="confirm_password" value={this.state.confirm_password} onChange={this.updateInput}/>
<span className="focus-input100"></span>
</div>
<div className="container-login100-form-btn">
<button className="login100-form-btn">
Register
</button>
</div>
<div className="flex-sb-m w-full p-b-48 m-t-60 text-center">
<label>
Already have an account ?
<a className="txt3 m-l-5" href="/login">
Sign In Now
</a>
</label>
</div>
</form>
</div>
</div>
</div>
);
}
}

我有以下路线,
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});

Route::post('users',array( 'middleware'=>'cors','uses'=>'Auth\RegisterController@registerUser'));
Route::get('users',array( 'middleware'=>'cors','uses'=>'Auth\RegisterController@getUsers'));

这是 CORS 中间件,
<?php

namespace App\Http\Middleware;

use Closure;

class CORS
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
header('Access-Control-Allow-Origin: http://localhost:3000/');
header('Access-Control-Allow-Credentials: true');

// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];

if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}

$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);

return $next($request);
}
}

最后这里是用户创建功能
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}

protected function registerUser(Request $request)
{
$data = $request->all();
return response()->json($this->create($data));
}

当我从 react app 发送 post 请求时,控制台显示以下错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://incomeexpense.stacklearning.com/api/users. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

TypeError: "NetworkError when attempting to fetch resource." Register.js:39 Cross-Origin Request Blocked:

The Same Origin Policy disallows reading the remote resource at http://incomeexpense.stacklearning.com/api/users. (Reason: CORS request did not succeed).



我知道这个错误是由于不同的域和浏览器阻止了对不同域的资源访问。

我只想知道我需要在前端和后端做什么才能把事情做好

PS:后端代码在从 postman 发送请求时完美运行。

最佳答案

URI 架构不匹配
Origin请求 header 设置在 headers 中您的提取请求的接口(interface)包含主机:localhost:3000 .在 CORS 中间件中配置的 Access-Control-Allow-Origin CORS header 包含主机:http://localhost:3000/ .在获取请求和 CORS 中间件中,定义的 URI 方案/主机/端口元组必须完全匹配。

将您的两个 URL 更改为 http://localhost:3000
见:Fetch Spec , CORS SpecCORS for Developers

Chrome 错误

请注意,Chrome 不支持 localhost 的 CORS 请求.您可以找到记录在案的 Chrome 错误 here .如果需要,错误中列出了一些解决方法。

关于reactjs - 类型错误 : "NetworkError when attempting to fetch resource.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51701630/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com