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);
        }

    }
}
相关推荐
damoluomu9 小时前
挑 PHP CMS 之前,先学会看它的协议
php
码兄科技14 小时前
24小时自助健身房系统软件开发实战指南:功能设计与部署方案
java·spring boot·uni-app
2501_9160074715 小时前
苹果商店iOS应用上架费用全面解析:开发者计划与审核费用计算
android·ios·小程序·https·uni-app·iphone·webview
2501_9160088916 小时前
如何实现iOS App代码混淆:SwiftShield使用指南
android·ios·小程序·https·uni-app·iphone·webview
子非鱼a17 小时前
【WEB】Online ToolWEB
php
PHP实战开发录18 小时前
Nginx上传大文件为什么报413
nginx·php·开发
2501_9160088918 小时前
怎么用 Godot 导出 iOS 应用并上架 App Store?签名字段该填什么?
android·ios·小程序·https·uni-app·iphone·webview
damoluomu1 天前
国产企业级 PHP CMS:哪些能免费商用
php
郑州光合科技余经理1 天前
同城外卖小程序开发:下单成功后,后台导出能不能对上用户端状态
开发语言·前端·git·后端·uni-app·php·ai编程
MyFreeIT1 天前
Android PHP Manual
php