Laravel 5.4 api 允许跨域访问

Laravel 5.4 api 允许跨域访问

需求: SPA单页应用请求接口, 报错

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' is therefore not allowed access.

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

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

'Access-Control-Allow-Origin: *'

文本使用Laravel 5.4版本

第一步: 创建中间件

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

app/Http/Middleware/AccessControlAllowOrigin.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class AccessControlAllowOrigin
{
    /**
     *
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $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` 这个别名.

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

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

app/Http/Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel 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 = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\AccessControlAllowOrigin::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
            'cors'
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'cors' => \App\Http\Middleware\AccessControlAllowOrigin::class,
    ];
}

帝国金的菜园子
分享一些工作学习中的经验
188 声望
3 粉丝
0 条评论
推荐阅读
win10 docker laradock 搭建PHP“简易”开发环境
安装windows版本docker,并且安装,这里我选择使用hyperV【官网】:[链接]下载laradock【github】:[链接] {代码...} 进入laradock文件夹复制.env.example到.env打开.env,按需进行一些调整,比如: {代码...} 按...

小金子阅读 469

程序猿必读-防范CSRF跨站请求伪造
CSRF(Cross-site request forgery,中文为跨站请求伪造)是一种利用网站可信用户的权限去执行未授权的命令的一种恶意攻击。通过伪装可信用户的请求来利用信任该用户的网站,这种攻击方式虽然不是很流行,但是却...

mylxsw22阅读 15.2k评论 12

再也不学AJAX了!(三)跨域获取资源 ① - 同源策略
「再也不学 AJAX 了」是一个以 AJAX 为主题的系列文章,希望读者通过阅读本系列文章,能够对 AJAX 技术有更加深入的认识和理解,从此能够再也不用专门学习 AJAX。本篇文章为该系列的第四篇,最近更新于 2023 年 1...

libinfs19阅读 4.1k评论 4

封面图
再也不学 AJAX 了!(一)AJAX 概述
跨域获取数据:介绍了与「跨域发送 AJAX 请求」相关的一些内容:例如「同源策略」与四种跨域请求资源的方式:JSONP,CORS,postMessage 和 WebSocket;

libinfs22阅读 4k评论 6

封面图
Eolink: 数字化企业连接世界的第一接口|开发者说
2015 年底,刘昊臻想更好地管理团队内部的 API,但市面上的产品并不能满足需求,于是,他决定做个产品来解决 API 协作问题。没想到,这个产品不仅解决了自己的麻烦,还可以解决所有 IT 团队遇到的有关 API 的共同...

万事ONES4阅读 12.7k

封面图
使用 `postMessage` 跨域名迁移 `localStorage`
朋友的网站有个需求:要从 A 域名迁移到 B 域名。所有内容不变,只是更改域名。这个需求不复杂,理论上改下配置然后 301 即可。但这个网站是纯静态网站,用户数据都存在 localStorage 里,所以他希望能够自动帮用...

Meathill6阅读 558评论 5

封面图
3 分钟上手,不用再找 Chatgpt 资源了,这里全都有
最近无论是打开社交网站,还是朋友圈,就连中午吃个饭都能听到大家都在聊 Chatgpt,仿佛如果这一刻你不懂这是个啥玩意儿,你就会觉得自己完全搭不上他们的话...

Postcat4阅读 738评论 5

封面图
188 声望
3 粉丝
宣传栏