Home >PHP Framework >ThinkPHP >An article explains in detail how thinkphp6 solves cross-domain problems through global middleware

An article explains in detail how thinkphp6 solves cross-domain problems through global middleware

藏色散人
藏色散人forward
2021-09-19 16:49:574741browse

The followingthinkphp frameworkThe tutorial column will introduce to you how thinkphp6 solves cross-domain problems through global middleware. I hope it will be helpful to friends in need!

tp6 Solve cross-domain problems through global middleware

tp6 official website provides a cross-domain resolution method, but it cannot be used when I use it directly. (Maybe my posture is wrong).

The front end sends an ajax request in Hbuildert, and cross-domain occurs.

Get request: It can be solved through background settings.
'Access-Control-Allow-Origin: *'。
Post request: OPTIONS request will occur. Add a header information to the ajax request.
header:{
    'Content-Type':'application/x-www-form-urlencoded'
}

Define middleware

<?php declare (strict_types = 1);

namespace app\middleware;
use think\Response;

/**
 * 全局跨域请求处理
 * Class CrossDomain
 * @package app\middleware
 */

class CrossDomain
{
    public function handle($request, \Closure $next)
    {
        header(&#39;Access-Control-Allow-Origin: *&#39;);
        header(&#39;Access-Control-Max-Age: 1800&#39;);
        header(&#39;Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE&#39;);
        header(&#39;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&#39;);
        if (strtoupper($request->method()) == "OPTIONS") {
            return Response::create()->send();
        }

        return $next($request);
    }
}

Add the middleware we defined in middleware.php

An article explains in detail how thinkphp6 solves cross-domain problems through global middleware

Then Cross-domain works just fine!

The above is the detailed content of An article explains in detail how thinkphp6 solves cross-domain problems through global middleware. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete