首页 技术 正文
技术 2022年11月17日
0 收藏 444 点赞 2,419 浏览 1609 个字

最近用thinkphp做项目,在测试环境时,存在接口的测试问题。在tp官网也没能找到相关的解决方法。自已看了一下源码,有如下的解决方案。

在项目目录下面,创建common/behavior/CronRun.php文件,文件内容如下:

<?php
/**
* Created by PhpStorm.
* User: LiuYang
* Date: 2017/3/9
* Time: 19:37
*/namespace app\common\behavior;use think\Exception;
use think\Response;class CronRun
{
public function run(&$dispatch){
$host_name = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : "*";
$headers = [
"Access-Control-Allow-Origin" => $host_name,
"Access-Control-Allow-Credentials" => 'true',
"Access-Control-Allow-Headers" => "x-token,x-uid,x-token-check,x-requested-with,content-type,Host"
];
if($dispatch instanceof Response) {
$dispatch->header($headers);
} else if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$dispatch['type'] = 'response';
$response = new Response('', 200, $headers);
$dispatch['response'] = $response;
}
}
}

接着在项目中(tags.php)配置行为动作,如下:

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------// 应用行为扩展定义文件
return [
// 应用初始化
'app_init' => [],
// 应用开始
'app_begin' => [
'app\\common\\behavior\\CronRun'
],
// 模块初始化
'module_init' => [],
// 操作开始执行
'action_begin' => [],
// 视图内容过滤
'view_filter' => [],
// 日志写入
'log_write' => [],
// 应用结束
'app_end' => [
'app\\common\\behavior\\CronRun'
],
];

ok,以上几步就解决跨域请求问题。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289