laravel-API解决跨域问题

laravel-API解决跨域问题

Access to XMLHttpRequest at 'http://mysite2.test/api/authorizations' from origin 'http://localhost:9529' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

创建中间件

创建app/Http/Middleware/Cors.php,设置响应头信息

<?php
/**
 * +--------------------------------------------------------+
 * @Created by PhpStorm.
 * @Category Cors.php
 * @Depiction:
 * Author: huangwy
 * Date: 2020/12/8  15:17
 * +--------------------------------------------------------+
 */

namespace App\Http\Middleware;


use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 设置允许访问的域地址
        $domains = [
            'http://localhost:9527',
            'http://localhost:9528',
            'http://localhost:9529',
            'http://mysite2.test',
            'https://mysite3.test',
        ];
        // 判断请求头中是否包含ORIGIN字段
        if(isset($request->server()['HTTP_ORIGIN'])){
            $origin = $request->server()['HTTP_ORIGIN'];
            if (in_array($origin, $domains)) {
                //设置响应头信息
                header('Access-Control-Allow-Origin: '.$origin);
                header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
            }
        }

        return $next($request);
    }

}

注册路由,增加中间件

protected $middleware中添加

 \App\Http\Middleware\Cors::class

protected $routeMiddleware中添加

 'cors' => \App\Http\Middleware\Cors::class
'api' => [
            'throttle:60,1',
            'cors',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值