在流明中启用CORS [英] Enable CORS in lumen
本文介绍了在流明中启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有使用流明开发的API.我可以使用邮递员得到请求.但是当使用Jquery.ajax进行请求时,它不起作用.因此,我需要知道如何在流明API中启用CORS.
I have API developed using lumen. I can get request using postman. But when request using Jquery.ajax it is not working. So I need to know how to enable CORS in lumen API.
推荐答案
请考虑使用以下代码创建CorsMiddleware.php
文件.在此处找到详细信息.
Consider creating a CorsMiddleware.php
file with the following code. Find detail here.
<?php namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
{
$response->header($key, $value);
}
return $response;
}
}
将其保存在中间件文件夹中后,通过将其添加到中间件列表中的bootstap/app.php
文件中来启用它,如下所示:
After saving it in your middleware folder, enable it by adding it to your bootstap/app.php
file, on the list of you middleware like this
$app->middleware([
...
App\Http\Middleware\CorsMiddleware::class // Add this
]);
希望对您有帮助.
这篇关于在流明中启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文