在流明中启用 CORS [英] Enable CORS in lumen

查看:46
本文介绍了在流明中启用 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 lumen 开发了 API.我可以使用邮递员获取请求.但是当使用 Jquery.ajax 请求时它不起作用.所以我需要知道如何在 lumen 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆