laravel-API解决跨域问题

这篇博客介绍了如何在 Laravel 中通过创建自定义中间件来解决API的跨域问题。详细步骤包括在 `app/Http/Middleware` 目录下创建 `Cors.php` 文件,设置允许的域名,并在请求处理中添加响应头信息。之后,将中间件添加到 `protected $middleware` 和 `protected $routeMiddleware` 中,确保在API路由上应用该中间件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,
        ],
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值