直接上代码
在后台写 允许跨域的域名,
$allowedDomains = array("https://example1.com", "https://example2.com");
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
if (in_array($origin, $allowedDomains)) {
    header("Access-Control-Allow-Origin: " . $origin);
} else {
    header("HTTP/1.1 403 Forbidden");
    die("Access denied");
}
完全解决跨域问题,允许一切请求
header("Access-Control-Allow-Origin: *");
上代码
<?php
 
namespace app\api\controller;
use think\Db;
use think\Session;
use think\Controller;
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Headers:Origin,X-Requested-With,Content-Type,Accept");
class Index extends Controller
{
 
 
    public function index()
    {
       var_dump(11);die;
    }
    
    public function reg()
    {
       var_dump($_REQUEST);die;
    }
  
}
如果是 thinkphp框架,在public/index.php文件里面 namespace think;下面些
//允许跨域
// === CORS(支持凭证)开始 ===
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
// 允许的前端域名白名单(按你实际前端域名填写)
$allowOrigins = [
 
    'http://localhost:1617',   // 本地调试可选
];
 
if ($origin && in_array($origin, $allowOrigins, true)) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,PATCH,OPTIONS");
    header("Access-Control-Allow-Headers: DNT,Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization,X-Requested-With,Platform,token");
    header("Vary: Origin"); // 让代理/缓存按来源区分
}
// 预检请求直接放行并返回 204(必须带上相同的 CORS 头)
if (strtoupper($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    http_response_code(204);
    header("Content-Length: 0");
    exit();
}
// === CORS 结束 ===
//end