我正在尝试向外部 laravel 站点发出 2 个 ajax 请求。其中一个请求完美运行(“列表”)。另一个(“savedevice”)给我以下错误:
访问 XMLHttpRequest 位于 'http://localhost/somesite/devicecreate' 来自来源 'null' 已被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。
origin 为 null,因为请求来自本地 html。
我已经创建了一个适用于第一个路由但不适用于第二个路由的 CORS 中间件解决方案。
这2条路由存储在web.php中,如下所示:
Route::post('/devicecreate','FrontEndController@savedevice')->middleware('cors');
Route::post('/list', 'FrontEndController@list')->middleware('cors');
这是我在 javascript 中的 ajax 请求函数
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);
};
目前(出于测试目的)两种路由方法都执行相同的操作。但只有“/list”有效。
如果我尝试 php工匠路线:列表我可以看到“devicecreate”和“list”具有相同的方法、正确的操作和相同的中间件
我的 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)
{
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路由:缓存.
我尝试过重命名路线,但没有什么区别。
有人可以帮忙吗?