下面thinkphp框架教程栏目将给大家介绍thinkphp6如何通过全局中间件解决跨域问题,希望对需要的朋友有所帮助!
tp6 通过全局中间件 解决跨域问题
tp6官网有提供跨域决绝方法,当我直接使用无法用。(可能我用的姿势不对)。前端在hbuildert中发送ajax请求,发生跨域。
get请求:可以通过后台设置解决。'access-control-allow-origin: *'。
post请求:会发生options请求。在ajax请求中添加一个header头信息。header:{ 'content-type':'application/x-www-form-urlencoded'}
定义中间件<?phpdeclare (strict_types = 1);namespace app\middleware;use think\response;/** * 全局跨域请求处理 * class crossdomain * @package app\middleware */class crossdomain{ 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'); if (strtoupper($request->method()) == options) { return response::create()->send(); } return $next($request); }}
在middleware.php中加入我们定义的中间件
然后跨域就好使了!
以上就是一文详解thinkphp6如何通过全局中间件解决跨域问题的详细内容。