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

    }
}
相关推荐
汤米粥18 分钟前
小皮PHP连接数据库提示could not find driver
开发语言·php
fakaifa2 小时前
CRMEB Pro版v3.1源码全开源+PC端+Uniapp前端+搭建教程
前端·小程序·uni-app·php·源码下载
转角羊儿2 小时前
uni-app请求方法封装⑦
uni-app
java知路2 小时前
uniapp h5实现录音
uni-app
haodanzj4 小时前
在uniapp中封装请求接口 (带刷新token)
前端·javascript·uni-app
空&白5 小时前
uniapp h5地址前端重定向跳转
前端·uni-app
工业互联网专业5 小时前
Python毕业设计选题:基于Django+uniapp的公司订餐系统小程序
vue.js·python·小程序·django·uni-app·源码·课程设计
家里有只小肥猫5 小时前
关于vue生命周期
uni-app·uniapp
不法5 小时前
uniapp 跨域前端代理
前端·uni-app
万岳软件开发小城5 小时前
外卖跑腿APP开发实战:如何基于同城O2O系统源码搭建平台
php·app开发·同城o2o系统源码·同城外卖跑腿系统源码·外卖平台开发·外卖app