Laravel 5:仅在一个URL上路由CORS问题 [英] Laravel 5: routing CORS issue on just one URL
问题描述
我正在尝试向外部laravel网站发出2个Ajax请求.其中一个请求可以正常工作(列表").另一个(保存设备")给我以下错误:
I am trying to make 2 ajax requests to an external laravel site. One of the requests works perfectly ("list"). The other one ("savedevice") gives me the following error:
从原始站点' http://localhost/somesite/devicecreate '访问XMLHttpRequest空"已被CORS策略阻止:所请求的资源上没有"Access-Control-Allow-Origin"标头.
Access to XMLHttpRequest at 'http://localhost/somesite/devicecreate' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
原点为空,因为请求来自本地html.
The origin is null because the request comes from a local html.
我已经创建了一个CORS中间件解决方案,该解决方案适用于第一条路线,但不适用于第二条路线.
I have already created a CORS middleware solution that works for the first route but not the second.
这2条路由存储在web.php中,如下所示:
The 2 routes are stored in web.php as follows:
Route::post('/devicecreate','FrontEndController@savedevice')->middleware('cors');
Route::post('/list', 'FrontEndController@list')->middleware('cors');
这是我在javascript中的ajax请求函数
Here is my ajax request function in javascript
var ajaxRequest = function ( url, data, callback ) {
var xhr = new XMLHttpRequest();
xhr.onerror = function(e) {
console.log("Ajax request error");
};
xhr.addEventListener("load",function () {
xhr.responseJSON = JSON.parse( xhr.responseText );
callback( xhr.responseJSON);
});
xhr.open("POST", url );
xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");
xhr.send(data);
};
目前(出于测试目的),两种路由方法都做同样的事情.但是只有"/列表"有效.
At the moment (for testing purposes) both route methods do the same thing. But only "/list" works.
如果我尝试使用php artisan route:list ,则可以使用相同的方法,正确的操作和相同的中间件看到"devicecreate"和"list"
If I try php artisan route:list I can see both "devicecreate" and "list" with the same Methods, correct Actions and same Middleware
我的CORS中间件如下:
My CORS middleware looks like this:
<?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)
{
if ($request->getMethod() == "OPTIONS") {
return response(['OK'], 200)
->withHeaders([
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET,POST',
'Access-Control-Allow-Headers' => 'Authorization,Content-Type,X-Requested-With,XMLHttpRequest',
]);
}
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET,POST')
->header('Access-Control-Allow-Headers','Authorization,Content-Type,X-Requested-With,XMLHttpRequest');
}
}
我还尝试运行php artisan route:cache .
I also tried to run php artisan route:cache.
我尝试重命名该路线,但这没什么区别.
I have tried renaming the route but it makes no difference.
任何人都可以帮忙吗?
推荐答案
24小时后,我为遇到以下任何情况的任何人提供了解决方案:
24 hours later I have the solution for anybody experiencing any of the following:
- CORS/跨域错误从外部来源发布ajax(否则请参见)
- 419未知状态
- 从外部站点发布时,发出周围的CSRF令牌.
1)创建一个CORS中间件( https://laravel.com/docs/5.8/middleware ).您可以使用上面显示的我的中间件代码.
1) create a CORS middleware (https://laravel.com/docs/5.8/middleware). You can use my middleware code displayed above.
2)确保将中间件添加到受保护的$ routeMiddleware下的Http/Kernal.php文件中,例如: 'cors'=>\ App \ Http \ Middleware \ Cors :: class,
2) Make sure you add the middleware to the Http/Kernal.php file under protected $routeMiddleware, for example:
'cors' => \App\Http\Middleware\Cors::class,
3)仅将中间件附加到需要它的路由.就我而言,这是:
3) Attach the middleware only to the routes that need it. In my case this is:
Route::post('/setdevice','FrontEndController@savedevice')->middleware('cors');
Route::post('/list', 'FrontEndController@list')->middleware('cors');
4)请记住从CSRF令牌验证中排除您的外部Ajax请求!我的问题是我忘记添加第二条路线了!因此,就我而言,我将它们添加到了Http/Middleware/VerifyCsrfToken.php中受保护的$ except参数中:
4) Remember to exclude your external Ajax requests from the CSRF Token verification! My problem is I had forgotten to add the second route!! So in my case I added these to the protected $except parameter in Http/Middleware/VerifyCsrfToken.php:
protected $except = [
'list',
'savedevice',
];
这篇关于Laravel 5:仅在一个URL上路由CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!