• Laravel API跨域访问的实现步骤


    本篇文章给大家带来的内容是关于Laravel API跨域访问的实现步骤,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

    服务器A请求服务器B的接口,那么一般会出现跨域问题。

    1

    XMLHttpRequest cannot load http://api.console.vms3.com/api/user. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' istherefore not allowed access.

    意思就是服务器响应不允许跨域访问.

    那我们就需要让服务器支持跨域访问, 也就是在响应头部中添加

    1

    'Access-Control-Allow-Origin: *'

    第一步: 创建中间件

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    创建 `app/Http/Middleware/AccessControlAllowOrigin.php` middleware 把 'Access-Control-Allow-Origin: *' 写入头部.

    app/Http/Middleware/AccessControlAllowOrigin.php

    <?php

     

    namespace AppHttpMiddleware;

     

    use Closure;

    use IlluminateSupportFacadesAuth;

     

    class AccessControlAllowOrigin

    {

        /**

         *

         * Handle an incoming request.

         *

         * @param  IlluminateHttpRequest  $request

         * @param  Closure  $next

         * @return mixed

         */

        public function handle($request, Closure $next)

        {

            header('Access-Control-Allow-Origin: *');

            header("Access-Control-Allow-Credentials: true");

            header("Access-Control-Allow-Methods: *");

            header("Access-Control-Allow-Headers: Content-Type,Access-Token");

            header("Access-Control-Expose-Headers: *");

     

            return $next($request);

        }

     

    }

    第二步: 注册路由

    注册这个 middleware 到 kernel 中. 
    分别在 protected $middleware 数组中和 protected $routeMiddleware 数组中
    添加我们刚才创建的那个文件class名, 使用 cors 这个别名.

    链接:https://pan.baidu.com/s/1v5gm7n0L7TGyejCmQrMh2g 提取码:x2p5

    免费分享,但是X度限制严重,如若链接失效点击链接或搜索加群 群号518475424

    第三步: 设置中间件保护接口

    然后在设置它保护 api , 就是$middlewareGroups['api'] 的数组中添加它的别名, 本文中是 'cors'
    app/Http/Kernel.php

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    <?php

     

    namespace AppHttp;

     

    use IlluminateFoundationHttpKernel as HttpKernel;

     

    class Kernel extends HttpKernel

    {

        /**

         * The application's global HTTP middleware stack.

         *

         * These middleware are run during every request to your application.

         *

         * @var array

         */

        protected $middleware = [

            IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,

            IlluminateFoundationHttpMiddlewareValidatePostSize::class,

            AppHttpMiddlewareTrimStrings::class,

            IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,

            AppHttpMiddlewareAccessControlAllowOrigin::class,

        ];

     

        /**

         * The application's route middleware groups.

         *

         * @var array

         */

        protected $middlewareGroups = [

            'web' => [

                AppHttpMiddlewareEncryptCookies::class,

                IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,

                IlluminateSessionMiddlewareStartSession::class,

                // IlluminateSessionMiddlewareAuthenticateSession::class,

                IlluminateViewMiddlewareShareErrorsFromSession::class,

                AppHttpMiddlewareVerifyCsrfToken::class,

                IlluminateRoutingMiddlewareSubstituteBindings::class,

            ],

     

            'api' => [

                'throttle:60,1',

                'bindings',

                'cors'

            ],

        ];

     

        /**

         * The application's route middleware.

         *

         * These middleware may be assigned to groups or used inpidually.

         *

         * @var array

         */

        protected $routeMiddleware = [

            'auth' => IlluminateAuthMiddlewareAuthenticate::class,

            'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,

            'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,

            'can' => IlluminateAuthMiddlewareAuthorize::class,

            'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,

            'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,

            'cors' => AppHttpMiddlewareAccessControlAllowOrigin::class,

        ];

    }

    第四步:在路由中添加路由

    1

    2

    3

    Route::middleware('cors')->group(function () {

        //

    });

    以上就是Laravel API跨域访问的实现步骤的详细内容。

  • 相关阅读:
    C#中AppDomain.CurrentDomain.BaseDirectory及各种路径获取方法
    Sqlserver查询数据库文件大小和剩余空间
    【免费视频】使用VS Code开发ASP.NET Core WebAPI应用程序
    WinForm自动记录从上次关闭位置启动窗体
    c#通过socket判断服务器连接是否正常
    ASP.NET Core Windows服务开发技术实战演练
    win7/win10 设置始终以管理员身份运行cmd窗口
    投资回报率,止损率
    等额本息,等额本金,先息后本解读
    银行加息有什么影响(央行加息,对股市和房价有何影响?)
  • 原文地址:https://www.cnblogs.com/it-3327/p/11784589.html
Copyright © 2020-2023  润新知