CORS代码解决方案

namespace app\index\behavior;



use think\Response;

class CORS
{


    public function run(&$dispatch)
    {
        $host_name = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : "*";
            $headers = [
                "Access-Control-Allow-Origin" => $host_name,
                "Access-Control-Allow-Credentials" => 'true',
                "Access-Control-Allow-Headers" => "x-token,x-uid,x-token-check,x-requested-with,content-type,Host,token, Origin, Accept, Authorization",
                "Access-Control-Allow-Methods"=>"GET, POST, PUT, DELETE, PATCH, OPTIONS'",
            ];
            if ($dispatch instanceof Response) {
                $dispatch->header($headers);
            } else if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
                $dispatch['type'] = 'response';
                $response = new Response('', 200, $headers);
                $dispatch['response'] = $response;

        }

    }

}

application下的tags.php

return [
    // 应用初始化
    'app_init'     => [],
    // 应用开始
    'app_begin'    => [],
    // 模块初始化
    'module_init'  => [],
    // 操作开始执行
    'action_begin' => [],
    // 视图内容过滤
    'view_filter'  => [],
    // 日志写入
    'log_write'    => [],
    // 应用结束
    'app_end'      => ['app\\index\\behavior\\CORS'],
];

假如谷歌浏览器请求、正常跨域默认谷歌浏览器会替你用options请求一下。

options 返回服务器针对特定资源所支持的HTTP请求方法。

如果代码是如下这么写。那么什么数据都获取不到

    public function getNewCourses(Request $request)
    {
        if( $request->isPost() && $request->isAjax()){
            $course=Db::name('courses')->order('id desc')
                ->field('id,img,price,click,title')
                ->limit(4)->select()->toArray();

           echo json_encode($course);
        }
    }

当谷歌浏览器发送完options请求后。会把你的请求在发送一次给服务器地址。然而用jquery中的ajax方法发现没有任何返回数据。

修改PHP代码

    public function getNewCourses(Request $request)
    {
        if( $request->isPost() && $request->isAjax()){
            $course=Db::name('courses')->order('id desc')
                ->field('id,img,price,click,title')
                ->limit(4)->select()->toArray();

           echo json_encode($course);
        }else{
            if($request->isAjax()){
                echo "ajax";
            }else{
                echo "no";
            }
        }
    }

结果发现

图

解决办法

解决方法1、PHP代码去掉请求方法的判断

    public function getNewCourses(Request $request)
    {
       
            $course=Db::name('courses')->order('id desc')
                ->field('id,img,price,click,title')
                ->limit(4)->select()->toArray();

           echo json_encode($course);

    }

解决方法2、在前端js代码中解决

    $.ajax({
        url:'http://dong.wk.cn:83/index/api/getNewCourses',
        type:'POST',
        dataType:'JSON',
        headers:{"Content-Type":"text/plain;charset=UTF-8","X-Requested-With":"XMLHttpRequest "},
        data:{},
        success:function(result){

手动添加headers

headers:{"Content-Type":"text/plain;charset=UTF-8","X-Requested-With":"XMLHttpRequest "}

再次请求

图

Last modification:January 31, 2020
如果觉得我的文章对你有用,请随意赞赏