类型错误:“尝试获取资源时出现网络错误."
[英] TypeError: "NetworkError when attempting to fetch resource."
本文介绍了类型错误:“尝试获取资源时出现网络错误."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现了很多与我的问题类似的问题,但我没有得到解决方案,这就是我在这里问的原因.
我刚刚开始学习使用 React 进行前端开发.我为在不同端口运行的前端和后端制作了单独的应用程序.
后端:运行在 incomeexpense.stacklearning.com/
的 Laravel 框架应用
前端:在 localhost:3000/
上运行的 React 应用程序
我有一个这样的表格:
import React,{Component} from 'react';导出默认类注册扩展组件{构造函数(道具){超级(道具);this.state = {姓名: '',电子邮件: '',密码: '',确认密码: ''}}更新输入 = (事件) =>{const name = event.target.name;const value = event.target.value;this.setState({[name]: value});}handleSubmit = (事件)=>{event.preventDefault();获取('http://incomeexpense.stacklearning.com/api/users',{方法:'POST',正文:JSON.stringify({名称:this.state.name,电子邮件:this.state.email,密码:this.state.password,确认密码:this.state.confirm_password}),标题:{"内容类型": "应用程序/json",来源":本地主机:3000",}}).then(函数(响应){控制台日志(响应);},函数(错误){控制台日志(错误);});}使成为(){返回(<div className="限制器"><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">报名</span><span className="txt1 p-b-11">姓名</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>
<span className="txt1 p-b-11">电子邮件</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>
<span className="txt1 p-b-11">密码</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>
<span className="txt1 p-b-11">确认密码</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 className="container-login100-form-btn"><button className="login100-form-btn">登记按钮>
<div className="flex-sb-m w-full p-b-48 m-t-60 text-center"><标签>已经有一个帐户?<a className="txt3 m-l-5" href="/login">立即登录</a>标签>
</表单>
);}}
我有以下路线,
Route::middleware('auth:api')->get('/user', function (Request $request) {返回 $request->user();});Route::post('users',array('middleware'=>'cors','uses'=>'Auth\RegisterController@registerUser'));Route::get('users',array('middleware'=>'cors','uses'=>'Auth\RegisterController@getUsers'));
这是 CORS 中间件,
'发布,获取,选项,放置,删除','Access-Control-Allow-Headers'=>'内容类型、X-Auth-Token、来源'];if($request->getMethod() == "OPTIONS") {//客户端应用程序只能设置 Access-Control-Allow-Headers 中允许的标头return Response::make('OK', 200, $headers);}$response = $next($request);foreach($headers as $key => $value)$response->header($key, $value);返回 $next($request);}}
最后是用户创建功能
受保护的函数 create(array $data){返回用户::创建(['名称' =>$data['name'],'电子邮件' =>$data['email'],'密码' =>bcrypt($data['password']),]);}受保护的函数 registerUser(Request $request){$data = $request->all();return response()->json($this->create($data));}
当我从 react app 发送 post 请求时,控制台显示以下错误
<块引用>跨源请求被阻止:同源策略不允许读取位于 http://incomeexpense 的远程资源.stacklearning.com/api/users.(原因:缺少 CORS 标头Access-Control-Allow-Origin").
TypeError:尝试获取资源时出现网络错误."注册.js:39跨域请求被阻止:
同源策略不允许读取位于 http://incomeexpense.stacklearning.com/api 的远程资源/用户.(原因:CORS 请求没有成功).
我知道这个错误是由于不同的域和浏览器阻止了对不同域的资源访问.
我只想知道我需要在前端和后端做什么才能把事情做好
PS:后端代码在从邮递员发送请求时完美运行.
解决方案
URI Schema Mismatch
在获取请求的 headers
接口中设置的 Origin
请求标头包含主机:localhost:3000
.在 CORS 中间件中配置的 Access-Control-Allow-Origin CORS 标头包含主机:http://localhost:3000/
.在获取请求和 CORS 中间件中,定义的 URI 方案/主机/端口元组必须完全匹配.
将两个 URL 更改为 http://localhost:3000
参见:获取规范、CORS 规范 和 面向开发者的 CORS
Chrome 错误
请注意,Chrome 不支持 localhost
的 CORS 请求.您可以在此处找到记录在案的 Chrome 错误.如果需要,错误中列出了一些解决方法.
I've found a lot of question similar to my problem but I don't get solution that's why I've asked here.
I've just started learning front end development using React. I've made separate app for front end and backend running at different ports.
Backend : Laravel framework app running at incomeexpense.stacklearning.com/
Frontend : React app running at localhost:3000/
I've a form like this:
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>
);
}
}
I've following routes,
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'));
Here is CORS middleware,
<?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);
}
}
Finally here is user creating function
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));
}
When I send the post request from react app following error is shown at console
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).
I know this error is due to different domain and browser prevent resource access to different domain.
I just want to know what I need need to do at front and at back end to make things right
PS: back end code works perfectly while sending request from postman.
解决方案
URI Schema Mismatch
The Origin
request header set within the headers
interface of your fetch request contains the host: localhost:3000
. The Access-Control-Allow-Origin CORS header that is configured within the CORS middleware contains the host: http://localhost:3000/
. The URI scheme/host/port tuple defined must be an exact match in both the fetch request and CORS middlewares.
Change both of your URLs to http://localhost:3000
See: Fetch Spec, CORS Spec and CORS for Developers
Chrome Bug
Just to note, Chrome does not support CORS Requests for localhost
. You can find the documented Chrome bug here. There are some workarounds listed within the bug, if need.
这篇关于类型错误:“尝试获取资源时出现网络错误."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文