tp6 解决跨域问题

在和前端js对接接口的时候遇到跨域问题,记录一下

方法一
通过route文件配置
文件位置 : app/api/route/app.php

<?php
/**
 * Created by PhpStorm.
 * User: 雪后西溏 <[email protected]>
 * Date: 2021-02-23
 * Time: 16:06
 */

use think\facade\Route;

// 手写资源路由
Route::group(':v/:c', function () {
    Route::get('', '/:v.:c/index');
    Route::get('create', '/:v.:c/create');
    Route::get(':id/edit', '/:v.:c/edit');
    Route::get(':id', '/:v.:c/read');
    Route::post('', '/:v.:c/save');
    Route::put(':id', '/:v.:c/update');
    Route::delete(':id', '/:v.:c/delete');
})->allowCrossDomain([
    /** 设置跨域允许的header头信息,新增token字段 */
    'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, authKey, Accept, Origin, token',
    /** 允许所有请求 */
    'Access-Control-Allow-Origin'      => '*',
    'Access-Control-Allow-Credentials' => 'true',
]);

更新后写法

<?php
/**
 * Created by PhpStorm.
 * User: 雪后西溏 <[email protected]>
 * Date: 2021-06-16
 * Time: 10:14
 */

use think\facade\Route;

// 开启资源路由
Route::resource(':v/:c', ':v.:c');
// 配置跨域
Route::allowCrossDomain([
    /** 设置跨域允许的header头信息 , 增加token字段 */
    'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, authKey, Accept, Origin, token',
    //    允许所有请求
    'Access-Control-Allow-Origin'      => '*',
]);

参见 官方文档
https://www.kancloud.cn/manual/thinkphp6_0/1037507

 

方法二

设置全局中间件

在 ./app/middleware.php 文件中启用内置中间件即可

\think\middleware\AllowCrossDomain::class
<?php
// 全局中间件定义文件
return [
    // 全局请求缓存
    // \think\middleware\CheckRequestCache::class,
    // 多语言加载
    // \think\middleware\LoadLangPack::class,
    // Session初始化
    // \think\middleware\SessionInit::class
    \think\middleware\AllowCrossDomain::class,
];

 

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Captcha Code