uni-app h5对接 thinkphp5接口跨域

uni-app h5对接 thinkphp5接口跨域

问题描述

  • 请求接口 提示
bash 复制代码
Access to XMLHttpRequest at 'http://*******' from origin 'http://localhost:8091' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

解决方案

  • application/tags.php
php 复制代码
<?php
return [
    // 应用初始化
    'app_init'     => [
        'app\\common\\behavior\\CORS'
    ],

];
  • application/common/behavior/CORS.php
php 复制代码
<?php
namespace app\common\behavior;

use think\Response;
class CORS
{
    public function appInit()
    {
        // Allow from any origin
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
            // you want to allow, and if so:
            header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');    // cache for 1 day
        }

        // Access-Control headers are received during OPTIONS requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                // may also be using PUT, PATCH, HEAD etc
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

            exit(0);
        }

    }
}
相关推荐
码间留白3 分钟前
鸿蒙 Web 播放器断流不报错:黑屏提示从 70 秒优化到 2 秒
uni-app·鸿蒙·直播·arkweb·鸿蒙os开发
FungLeo1 小时前
FengCMS · PHP+MySQL 升级实录· PHP Session 锁:什么时候释放能救活并发
android·mysql·php·session·fengcms
bufengwangluo18 小时前
企业上网行为管理:代理网关部署位置怎么选,策略怎么落
开发语言·php
wuxianda103020 小时前
4.3(a) 整改期素材从哪来:外包、素材站、AI 生成的内容怎么留证
uni-app·swift·4.3a·appstore审核
FungLeo21 小时前
FengCMS · PHP+MySQL 升级实录 · 输出转义的度:面包屑双重编码、默认转义与 cms_html()信任声明
mysql·html·php·fengcms·输出转义
FungLeo1 天前
FengCMS ·PHP+MySQL升级实录 · 富文本清洗配置实战:白名单、URI scheme、禁 iframe/id、实例缓存
mysql·缓存·php·xss·fengcms
苏琢玉1 天前
从 dsh-im 到微信:我做了个 PHP 包,让微信变成 AI 的消息入口
微信·php·composer
JaguarJack1 天前
php-wasm-builder 1.0 发布,让 PHP 应用在浏览器里运行
后端·php·服务端
BingoGo1 天前
php-wasm-builder 1.0 发布,让 PHP 应用在浏览器里运行
后端·php
FungLeo2 天前
FengCMS· PHP+MySQL升级实录 · 后台参数统一治理:id[]数组、id=undefined 跳转与312组回调组合
android·mysql·php·工程实践·fengcms