2019-08-13 18:14:11 190次浏览 4条回答 0 悬赏 10 金钱

尝试在Controllers加入behaviors(),未能解决。

public function behaviors()
{
    return ArrayHelper::merge([
        [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['*'],
                'Access-Control-Allow-Credentials' => true,
            ],
        ],
    ], parent::behaviors());
}

尝试在入口文件加入,未能解决。

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers:Authorization');
header("Access-Control-Allow-Methods: GET, POST, DELETE");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, X-Requested-With, Cache-Control,Authorization");
亿速云
  • 回答于 2019-08-13 18:44 举报

    这样写

    public function behaviors()
    {
        return ArrayHelper::merge([
            [
                'class' => Cors::className(),
                'cors' => [
                    'Origin' => ['*'],
                    'Access-Control-Request-Method' => ['GET', 'POST', 'HEAD', 'OPTIONS'],
    
                ],
            ],
        ], parent::behaviors());
    }
    
  • 回答于 2019-08-14 10:31 举报

    最简单的就是在前端域名上配置一个反向代理, 所有指向api的请求通通转发到你后端域名进行处理

  • 回答于 2019-08-14 16:07 举报

    亲测可用
    header('Access-Control-Allow-Origin:');
    header('Access-Control-Allow-Methods:
    ');
    header('Access-Control-Expose-Headers:*');
    header('Access-Control-Allow-Headers:x-requested-with,content-type,token');

  • 回答于 2019-08-15 09:22 举报

    1.`$response->headers->set('Access-Control-Allow-Origin', '*');

                $response->headers->set('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
                $response->headers->set('Access-Control-Request-Headers', 'Origin,X-Requested-With, Content-Type, Accept, Token');
                $response->headers->set('Access-Control-Expose-Headers', 'token');
                $response->headers->set('Access-Control-Allow-Headers', 'token');
                if (Yii::$app->request->getMethod() == 'OPTIONS') {
                    $response->setStatusCode(200);
                }`
    

    2.有token验证的话
    `public function behaviors()

    {
        $behaviors = ArrayHelper::merge(parent::behaviors(), [
            'authenticator' => [
                'class' => QueryParamAuth::className(),
                'tokenParam' => 'token',
            ]
        ]);
        $auth = $behaviors['authenticator'];
        unset($behaviors['authenticator']);
        $behaviors['corsFilter'] = [
            'class' => \yii\filters\Cors::className(),
        ];
        $behaviors['authenticator'] = $auth;
        $behaviors['authenticator']['except'] = ['options'];
        return $behaviors;
    }`
    
您需要登录后才可以回答。登录 | 立即注册
byebye
试用期

byebye

注册时间:2018-07-18
最后登录:2019-08-15
在线时长:2小时0分
  • 粉丝0
  • 金钱10
  • 威望0
  • 积分30

热门问题