laravel的跨域问题

大家好,我的前端是vue的,调用后端时涉及到跨域,在参考了这一篇之后,
博客:Laravel 跨域解决方案
我是这么写的,
1 新建一个中间件

php artisan make:middleware EnableCrossRequestMiddleware

2 书写中间件内容

<?php
namespace App\Http\Middleware;
use Closure;
class EnableCrossRequestMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
        $allow_origin = [
            'http://localhost:8081',
            'http://192.168.0.102:8081',
            'http://laraedu.yyii.info' 
        ];
        if (in_array($origin, $allow_origin)) {
            $response->header('Access-Control-Allow-Origin', $origin);
            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
            $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
            $response->header('Access-Control-Allow-Credentials', 'true');
        }
        return $response;
    }
}

3 然后在内核文件注册该中间件
App\Http\Kernel 类的 $middleware 属性添加,这里注册的中间件属于全局中间件

 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,
            \App\Http\Middleware\EnsureEmailIsVerified::class,      
        ],

        'api' => [
            \App\Http\Middleware\AcceptHeader::class,
            \App\Http\Middleware\EnableCrossRequestMiddleware::class, // <<--- 加这一行
            'throttle:60,1',
            'bindings',
        ],
    ];

然后本地调用,
首页没报跨域问题,登录时报跨域问题

线上,首页就报跨域问题,

如蒙指教,非常感谢!

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 3

线下的报错找个专业前端看一下就能解决了,至于线上的,明显你设置的可跨域列表不具有通用型,我记得这里应该是支持通配符的,不过使用通配符可能还会有别的问题,这个得自己解决了,因为造成这种报错的原因会有很多种,可能存在于各种地方,确实不好排查

3年前 评论

多谢@寻梦 ! 刚刚终于弄好这个,[满头大汗], 我以为代码里设置的不对,后来用nginx配置。参考了这一篇:nginx 配置add_header 'Access-Control-Allow-Origin' '*' 依然存在跨域问题blog.csdn.net/xiojing825/article/d... 使用了nginx之后,代码里就留了空。就这么个问题弄了一天....

3年前 评论

收藏一下,以后遇到了可以参考~

3年前 评论
phpervip (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!