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('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);
}
}
Add the middleware we defined in middleware.php

Then Cross-domain works just fine!




























