我使用 ionic v-3 应用程序和 laravel 5.5 作为后端 我的 ionic 应用程序中有一个获取请求
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Bearer '+localStorage.getItem('token')
})
};
this.prf=this.httpClient.get('http://localhost/blog/public/api/user',httpOptions);
它首先发送一个 OPTION
请求,然后在收到成功响应后发送一个 GET
请求
现在我在我的 api.php
文件中使用两个路由来处理这个问题
//first routing
Route::middleware('cors','auth:api')->get('/user', function (Request $request) {
return $request->user();
});
//second routing
Route::options('user', function(){
return response(200);
})->middleware('cors');
工作正常
我的请求头包含Access-Control-Request-Method: GET
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
Connection: keep-alive
Host: localhost
Origin: http://localhost:8100
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Mobile
Safari/537.36
在这篇文章中,它说 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
However, if the request is one that triggers a preflight due to the presence of the
Authorization
header in the request, you won’t be able to work around the limitation using the steps above. And you won’t be able to work around it at all unless you have control over the server the request is being made to.
还有其他方法/最佳实践来处理这个问题吗?
最佳答案
我找到了解决方案。
创建了一个中间件app/Http/Middleware/PreflightResponse.php
<?php
namespace App\Http\Middleware;
use Closure;
class PreflightResponse
{
/**
* 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('');
}
return $next($request);
}
}
添加app/Http/Kernel.php
'preflight' => \App\Http\Middleware\PreflightResponse::class,
但仍然在我的 api.php
中我必须使用这些代码
Route::middleware('cors','preflight')->group(function () {
Route::options('register', function(){});
Route::options('login', function(){});
Route::options('address', function(){});
Route::options('address/{id}', function(){});
Route::options('getaddress', function(){});
Route::options('getorders', function(){});
Route::options('order', function(){});
Route::options('orderdetails', function(){});
Route::options('user', function(){});
Route::options('profile', function(){});
Route::options('calendar', function(){});
Route::options('calendarapp', function(){});
});
关于angularjs - 如何在 Laravel 中处理预检请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49709210/