亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

THINKPHP跨域報(bào)錯(cuò)的解決方案

 更新時(shí)間:2024年03月06日 10:26:04   作者:yuanzelin8  
這篇文章主要介紹了THINKPHP跨域報(bào)錯(cuò)has been blocked by CORS policy: Response to preflight request doesn't pass access control check的解決方案,文中通過(guò)代碼示例給大家介紹的非常詳細(xì),需要的朋友可以參考下

報(bào)錯(cuò):has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

環(huán)境:thinkphp6 +nginx

今天和VUE配合調(diào)用接口的時(shí)候發(fā)現(xiàn)跨域報(bào)錯(cuò)。

參考

跨域請(qǐng)求 · ThinkPHP5.1完全開(kāi)發(fā)手冊(cè) · 看云

中間件 · ThinkPHP6.0完全開(kāi)發(fā)手冊(cè) · 看云

按照官網(wǎng)給出的例子,在中間件配置允許跨域

<?php
 
// 中間件配置
 
use think\middleware\AllowCrossDomain;
 
return [
    AllowCrossDomain::class
];
 

前端請(qǐng)求偶爾還是會(huì)出現(xiàn)了跨域請(qǐng)求提示

Access to XMLHttpRequest at from origin has been blocked by CORS policy: 
Request header field x-token is not allowed by 
Access-Control-Allow-Headers in preflight response.

php在批量導(dǎo)入excel數(shù)據(jù)更新時(shí)偶爾會(huì)出現(xiàn)這個(gè)問(wèn)題,出現(xiàn)時(shí)間不定,中間件都配置了跨域還是不行。

新建一個(gè)自定義的跨域中間件

<?php
 
namespace app\middleware;
use think\middleware\AllowCrossDomain;
 
 
class AllowCrossDomainMiddleware extends AllowCrossDomain
{
    // 加入自定義請(qǐng)求頭參數(shù) X-Token
    protected $header = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => 1800,
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, X-Token',
    ];
}

重新配置中間件

<?php
 
// 中間件配置
 
use think\middleware\AllowCrossDomain;
use app\middleware\AllowCrossDomainMiddleware;
 
return [
    // 不使用默認(rèn)的跨域中間件
    // AllowCrossDomain::class
 
    // 使用自定義跨域中間件
    AllowCrossDomainMiddleware::class
];
 

中間件,入口文件、路由都折騰了好幾遍不行。

最后解決辦法:

可以在入口文件添加以下代碼,單獨(dú)處理options請(qǐng)求

public/index.php

// 添加允許跨域請(qǐng)求頭
header("'Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: *");
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, X-Token");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH');
 
// 處理 OPTIONS 請(qǐng)求
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

以上就是THINKPHP跨域報(bào)錯(cuò)的解決方案的詳細(xì)內(nèi)容,更多關(guān)于THINKPHP跨域報(bào)錯(cuò)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論