码迷,mamicode.com
首页 > Windows程序 > 详细

Yii restful api跨域

时间:2017-11-16 11:38:21      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:namespace   filter   esc   ade   mod   -o   解决   collect   ret   

问题:NO ‘Access-Control_Allow-Origin‘ header is present on the requested resource.

解决方案


<?php

namespace app\modules\v1\controllers;

use Yii;
use yii\web\Response;

class BaseAPIController extends \yii\rest\Controller
{
    public $serializer = [
        ‘class‘ => ‘yii\rest\Serializer‘,
        ‘collectionEnvelope‘ => ‘items‘,
    ];
    
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors[‘contentNegotiator‘][‘formats‘] = [
            ‘application/json‘ => Response::FORMAT_JSON
        ];
        $behaviors[‘access‘] = [
            ‘class‘ => ‘yii\filters\AccessControl‘,
            ‘rules‘ => [
                [
                    ‘allow‘ => true,
                    ‘matchCallback‘ => function ($rule, $action) {
                        return in_array(Yii::$app->request->hostInfo, Yii::$app->params[‘acceptableHosts‘]);
                    }
                ]
            ]
        ];
        $behaviors[‘corsFilter‘] = [
            ‘class‘ => ‘yii\filters\Cors‘,
            ‘cors‘ => [
                ‘Origin‘ => Yii::$app->params[‘acceptableHosts‘],
                ‘Access-Control-Request-Method‘ => [‘GET‘, ‘POST‘, ‘PUT‘, ‘PATCH‘, ‘DELETE‘, ‘HEAD‘, ‘OPTIONS‘],
                ‘Access-Control-Request-Headers‘ => [‘*‘],
                ‘Access-Control-Allow-Credentials‘ => true,
                ‘Access-Control-Max-Age‘ => 86400,
                ‘Access-Control-Expose-Headers‘ => [],
            ],
        ];
        return $behaviors;
    }
}

 

Yii restful api跨域

标签:namespace   filter   esc   ade   mod   -o   解决   collect   ret   

原文地址:http://www.cnblogs.com/xiong63/p/7842711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!