tp6 跨域问题

1、app目录下的middleware

添加:\app\middleware\AllowCrossDomainMiddleware::class,

<?php
// 全局中间件定义文件
return [
    //全局跨域处理
    \app\middleware\AllowCrossDomainMiddleware::class,
];

2、app目录下的middleware目录中,添加中间件,AllowCrossDomainMiddleware.php

<?php
declare (strict_types = 1);

namespace app\middleware;
use think\middleware\AllowCrossDomain;
use think\Response;

class AllowCrossDomainMiddleware
{

    public function handle($request, \Closure $next)    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Max-Age: 1800');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, Token');
        return $next($request);
    }

}

3.在入口文件public/index.php中加

// 处理 OPTIONS 请求
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
    header("'Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: Token, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, X-Token");
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH');
    exit; // 直接退出,不走后序流程
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值