php 没有“Access-Control-Allow-Origin”标头 - Laravel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43565877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
No 'Access-Control-Allow-Origin' header - Laravel
提问by Kerry Ritter
XMLHttpRequest cannot load http://myapi/api/rating. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8104' is therefore not allowed access. The response had HTTP status code 403.
XMLHttpRequest 无法加载http://myapi/api/rating。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost:8104'。响应具有 HTTP 状态代码 403。
I can't figure out why I can't make CORS requests. I've install the middleware here, added it to the global http kernel, but it still doesn't work. Tried to create a custom middleware given stackoverflow suggestions but that also did not work. Also tried adding a Route group. Lastly, I tried setting the response headers manually in the request action. I'm really stuck - help is appreciated!
我不明白为什么我不能提出 CORS 请求。我已经在这里安装了中间件,将它添加到全局http内核中,但它仍然不起作用。尝试根据 stackoverflow 建议创建自定义中间件,但这也不起作用。还尝试添加一个路由组。最后,我尝试在请求操作中手动设置响应标头。我真的被困住了 - 感谢帮助!
See for code: https://gist.github.com/KerryRitter/0d7ababb7b9eb8d54f0ae55add9704a1
代码见:https: //gist.github.com/KerryRitter/0d7ababb7b9eb8d54f0ae55add9704a1
回答by Rahul Hirve
If you are using Laravel 5.5
& Laravel 5.x
and facing same problem like No 'Access-Control-Allow-Origin' header is present on the requested resource
. Just use following package and config your system.
如果您正在使用Laravel 5.5
&Laravel 5.x
并面临相同的问题,例如No 'Access-Control-Allow-Origin' header is present on the requested resource
. 只需使用以下软件包并配置您的系统。
Step 1:
第1步:
composer require barryvdh/laravel-cors
Step 2
第2步
You also need to add Cors\ServiceProvider
to your config/app.php
providers array:
您还需要添加Cors\ServiceProvider
到您的config/app.php
providers 数组:
FruitCake\Cors\CorsServiceProvider::class,
To allow CORS
for all your routes, add the HandleCors
middleware in the $middleware
property of app/Http/Kernel.php
class:
要允许CORS
所有路由,请HandleCors
在类的$middleware
属性中添加中间件app/Http/Kernel.php
:
For global uses:
供全球使用:
protected $middleware = [
// ...
\Fruitcake\Cors\HandleCors::class,
];
For middleware uses:
对于中间件用途:
protected $middlewareGroups = [
'web' => [
// ...
],
'api' => [
// ...
\Fruitcake\Cors\HandleCors::class,
],
];
Step 3
第 3 步
Once your installation completed run below command to publish the vendor files.
安装完成后,运行以下命令以发布供应商文件。
php artisan vendor:publish --provider="Fruitcake\Cors\ServiceProvider"
Hope this answer helps someone facing the same problem as myself.
希望这个答案可以帮助与我面临同样问题的人。
回答by Anubhav Tiwari
Laravel restricts the cross origin request due to security issues by default. We need to create a Cors middleware to the accept the request from different origin.
由于安全问题,Laravel 默认限制跨域请求。我们需要创建一个 Cors 中间件来接受来自不同来源的请求。
Step 1 : Create Cors middleware.
第 1 步:创建 Cors 中间件。
php artisan make:middleware Cors
Step 2 : Add below lines in handle function before return.
第 2 步:在返回前在 handle 函数中添加以下几行。
//header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Origin: http://localhost:4200');
header('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Authorization, Origin');
header('Access-Control-Allow-Methods: POST, PUT');
Step 3 : Register the middileware in app/Http/Kernel.php file.
第三步:在 app/Http/Kernel.php 文件中注册中间件。
Add below line in $middleware array
\App\Http\Middleware\Cors::class,
Step 4 : Now we have to call the middleware in app/Http/Kernel.php file
第 4 步:现在我们必须调用 app/Http/Kernel.php 文件中的中间件
Add below line in $routeMiddleware array
'cors' => \App\Http\Middleware\Cors::class,
回答by Jeevanantham Dharma
https://github.com/barryvdh/laravel-cors
https://github.com/barryvdh/laravel-cors
The laravel-cors package allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration.
laravel-cors 包允许您使用 Laravel 中间件配置发送跨源资源共享标头。
Features
特征
Handles CORS pre-flight OPTIONS requests Adds CORS headers to your responses
处理 CORS 飞行前选项请求 将 CORS 标头添加到您的响应中
回答by chanx_young
ok, here is my try. if i'm post to protected api using wrong token, passport return 401 with {"message":"Unauthenticated."}
好的,这是我的尝试。如果我使用错误的令牌发布到受保护的 api,则护照返回 401 并带有 {"message":"Unauthenticated."}
but because there is no cors header exist on response, my vue app get CORS error and cannot handle the response code.
但是因为响应中不存在 cors 标头,所以我的 vue 应用程序收到 CORS 错误并且无法处理响应代码。
so at laravel 5.8 on http/kernel.php $middlewarePriority add \Barryvdh\Cors\HandleCors::class before \App\Http\Middleware\Authenticate::class
所以在 http/kernel.php 上的 laravel 5.8 $middlewarePriority 在 \App\Http\Middleware\Authenticate::class 之前添加 \Barryvdh\Cors\HandleCors::class
here is my code:
这是我的代码:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:300,1',
'Localization',
'bindings',
'cors'
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
// Add Localization MiddleWare
'Localization' => \App\Http\Middleware\localization::class,
'cors' => \Barryvdh\Cors\HandleCors::class,
];
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
//add to handle cors before authenticate
\Barryvdh\Cors\HandleCors::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
hope this help someone else
希望这能帮助别人
回答by Talha Abrar
I faced this error in laravel 5.4 recently, i was sending ajax post request to my own website, and was still getting this same error, i faced this error due to two reasons to be precise,
我最近在 laravel 5.4 中遇到了这个错误,我正在向我自己的网站发送 ajax post 请求,但仍然遇到同样的错误,我遇到这个错误是由于两个确切的原因,
error: XMLHttpRequest cannot load https://[mydomain].com/quote/short. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[mydomain].com' is therefore not allowed access.
error: XMLHttpRequest cannot load https://[mydomain].com/quote/short. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[mydomain].com' is therefore not allowed access.
The reason for above error was that, i was posting request to http domain from https domain, so when i changed it to https, the error was resolved, then again i got the same error due to similar reason, which was the reason, this time, the domain had www.
and the requested one did not, after i added www.
to both, it worked like a charm.
上述错误的原因是,我是从 https 域向 http 域发布请求,所以当我将其更改为 https 时,错误得到了解决,然后由于类似的原因,我再次遇到了同样的错误,这就是原因,这个时间,域有www.
而请求的域没有,在我添加www.
到两者之后,它就像一个魅力。
And for cross origin requests, i used to following solution:
对于跨源请求,我习惯于以下解决方案:
Create a middleware (cors in my case) having code below
return $next($request) ->header('Access-Control-Allow-Origin', '*') ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
Insert middle-ware into routeMiddleware array in kernal.php
'cors' => \App\Http\Middleware\Cors::class,
Add middleware to the respected route
Route::get('myRoute', ['middleware' => 'cors' , 'uses'=> 'MyController@Action']
创建一个具有以下代码的中间件(在我的情况下为 cors)
return $next($request) ->header('Access-Control-Allow-Origin', '*') ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
将中间件插入到 kernal.php 中的 routeMiddleware 数组中
'cors' => \App\Http\Middleware\Cors::class,
将中间件添加到受尊重的路由
Route::get('myRoute', ['middleware' => 'cors' , 'uses'=> 'MyController@Action']
Hope this answer helps someone facing the same problem as myself.
希望这个答案可以帮助与我面临同样问题的人。
回答by Shirantha Madusanka
You can create Cors middleware class and add into the application's global HTTP middleware stack in kenel.php. Middlewares in this stack will run during every request to your application. After adding middleware into that stack you don't want to run it in api.php file. Follow thislink for more information.
您可以创建 Cors 中间件类并将其添加到 kenel.php 中应用程序的全局 HTTP 中间件堆栈中。此堆栈中的中间件将在对您的应用程序的每个请求期间运行。将中间件添加到该堆栈后,您不想在 api.php 文件中运行它。点击此链接了解更多信息。
回答by Amirouche Zeggagh
what you need actually is to add proxy to your application (front)
您实际上需要的是向您的应用程序添加代理(前面)
{
"/api/*": {
"target": "http://localhost:8000",
"secure": false,
"logLevel": "debug"
}
}
and in the package.json
并在 package.json 中
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
...
and start your project white this commend
并开始你的项目白这个推荐
npm start