React应用和Laravel API的CORS问题 [英] CORS Issue with React app and Laravel API
问题描述
我有一个React应用,该应用位于
以下解决方案应可解决与CORS相关的问题
第一步:创建新的中间件
Php artisan make:middleware cors
步骤2:
在创建的中间放置以下内容以替换handle方法
公共功能句柄($ request,闭包$下一个){
return $ next($ request)
-> header('Access-Control-Allow-Origin','*')
-> header( 'Access-Control-Allow-Methods','GET,POST,PUT,DELETE,OPTIONS')
-> header('Access-Control-Allow-Headers','Origin,Content-Type,Accept,授权,X-Request-With')
-> header('Access-Control-Allow-Credentials','true');
}
步骤3:
然后转到Kernel.php文件,并将其添加到应用程序的全局HTTP中间件堆栈下。
ps仅添加了带有注释的最后一行,其他行之前存在。
受保护的$ middleware = [
Illuminate\ \基础\Http\中间件\CheckForMaintenanceMode :: class,
\Illuminate\基础\Http\中间件\ValidatePostSize :: class,
\App\Http\ Middleware\TrimStrings :: class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull :: class,
\App\Http\Middleware\TrustProxies :: class ,
\App\Http\Middleware\Cors :: class,/// cors在此处添加
];
享受!
I have a React app which is at http://localhost:3000/
and Laravel API is at http://localhost/blog/public/api/
I get the following error
Access to fetch at 'http://localhost/blog/public/api/auth/signin' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Here are the response headers :-
I tried via htaccess, https://packagist.org/packages/barryvdh/laravel-cors
The below solution should fix the CORS related issue in Laravel.
Step1: Create a new middleware
‘Php artisan make:middleware cors’
Step 2:
Put the below in the created middle to replace the handle method
public function handle($request, Closure $next) {
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With')
->header('Access-Control-Allow-Credentials',' true');
}
Step 3:
Then go to Kernel.php file and add this under the The application's global HTTP middleware stack.
p.s. Only the last line with the comment was added, the other other lines exist before.
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\Cors::class,//cors added here
];
Enjoy!
这篇关于React应用和Laravel API的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!