Home > PHP Framework > ThinkPHP > body text

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

藏色散人
Release: 2021-09-19 16:49:57
forward
4716 people have browsed it

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: *'。
Copy after login
Post request: OPTIONS request will occur. Add a header information to the ajax request.
header:{
    'Content-Type':'application/x-www-form-urlencoded'
}
Copy after login

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);
    }
}
Copy after login

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!

Related labels:
php
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template