12

tp5允许跨域请求配置

 3 years ago
source link: https://www.leixuesong.com/3832
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

tp5允许跨域请求配置

PHP ThinkPHP教程 2020年6月18日

目前Web项目开发基本都是前后端分离的架构,那就避免不了会遇到跨域问题。在前端请求接口的时候,接口的协议、域名、端口三者之间任意一与当前页面地址不同就会出现跨域。跨域的时候会两次请求,第一次是 option去探测服务器是否允许跨域,然后才会正式去请求接口。ThinkPHP 5 是目前国内比较常用的PHP框架。下面雷雪松介绍两种tp5允许跨域请求的方法。

1、在TP5入口文件 index.php 配置。

1
2
3
4
5
6
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit;
}

2、通过TP5行为(Behavior)配置全局跨域
a、在base.php基类添加行为标签位

\think\Hook::listen('cros');

b、定义行为

1
2
3
4
5
6
7
8
namespace app\index\behavior;
class Cros{
public function run(&$params){
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
}
}

c、在目录下面或者模块的目录下面定义tags.php文件来统一定义行为

'cros' => [
'app\\api\\behavior\\Cros'
],

来源:tp5允许跨域请求配置


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK