解决:后端ThinkPHP5.1 实现跨域请求(前后端分离)

问题描述

当前后端分离开发时,会出现跨域请求被拒绝的情况(如Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response),这是由于请求URL中的header有不被允许跨域的元素;

解决

实现跨域请求可以在后端(TP5.1)的类初始化中实现;
如下,其中"Access-Control-Allow-Headers"是我问题中所举例被拒的配置,在后方加上元素"Content-Type"即可;
后续其他控制器继承 Cross 类即可实现跨域请求;

class Cross extends Controller
{
    //protected $userId;
    //初始化
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        //配置跨域请求
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, DELETE'); //请求方法
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Control-Type, Content-Type, token, Accept, x-access-sign, x-access-time');
        if (request()->isOptions()) {
            exit();
        }
    }
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页