hp66722667

hp66722667

这家伙有点懒,还没写个性签名!

  • 财富值1335
  • 威望值0
  • 总积分1565

个人信息

  • 2018-05-16 已签到
    连续签到3天,获得了15个金钱
  • 2018-05-15 已签到
    连续签到2天,获得了10个金钱
  • 2018-05-14 已签到
    连续签到1天,获得了5个金钱
  • 2018-05-12 已签到
    连续签到4天,获得了20个金钱
  • 2018-05-11 已签到
    连续签到3天,获得了15个金钱
  • 发表了说说
    好热闹,天天有人刷屏
  • 2018-05-10 已签到
    连续签到2天,获得了10个金钱
  • 在开发文档上找到了,当初是英文写的也就没特意的注意,现在发现真是恼火,浪费了半天时间找原因。
    以下是原文
    CORS
    Adding the Cross-Origin Resource Sharing filter to a controller is a bit more complicated than adding other filters described above, because the CORS filter has to be applied before authentication methods and thus needs a slightly different approach compared to other filters. Also authentication has to be disabled for the CORS Preflight requests so that a browser can safely determine whether a request can be made beforehand without the need for sending authentication credentials. The following shows the code that is needed to add the yii\filters\Cors filter to an existing controller that extends from yii\rest\ActiveController:
    `use yii\filters\auth\HttpBasicAuth;

    public function behaviors()
    {

    $behaviors = parent::behaviors();
    
    // remove authentication filter
    $auth = $behaviors['authenticator'];
    unset($behaviors['authenticator']);
    
    // add CORS filter
    $behaviors['corsFilter'] = [
        'class' => \yii\filters\Cors::className(),
    ];
    
    // re-add authentication filter
    $behaviors['authenticator'] = $auth;
    // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
    $behaviors['authenticator']['except'] = ['options'];
    
    return $behaviors;
    

    }`

    翻译
    CORS
    为控制器添加CORS(Cross-Origin Resource Sharing,跨域资源共享) 过滤器将比上面所述的过滤器要复杂一些,因为在身份验证之前就要应用CORS过滤器,这样就需要一个与其他过滤器略有不同的分支。对于CORS Preflight请求,身份验证必须被禁用,这样无需发送身份凭证浏览器就可以安全决定是否预先生成一个请求。为继承自yii\rest\ActiveController的控制器添加yii\filters\Cors过滤器的代码如下:
    `use yii\filters\auth\HttpBasicAuth;
    public function behaviors(){

    $behaviors=parent::behaviors();
    //移去身份验证过滤器
    $auth=$behaviors['authenticator'];
    unset($behaviors['authenticator']);
    //添加CORS过滤器
    $behaviors['corsFilter']=[
    	'class'	=>\yii\filters\Cors::className(),
    ];
    //重新添加身份验证过滤器
    $behaviors['authenticator']=$auth;
    //在CORS-pre-flight请求中避免使用身份验证(HTTP OPTIONS方法)
    $behaviors['authenticator']['except']=['options'];
    return $behaviors;
    

    }`
    最后放上手册的链接http://www.yiichina.com/doc/guide/2.0/rest-controllers#filters

  • 回复了 的回答

    贴请求配控制器方法的代码出来看看,是不是没有 return?

    谢谢啊,自己在开发文档上找到答案了

  • QQ图片20180509133659.png
    试着把api的认证关了,发现不报错了,这个是什么鬼,难道认证了就不让做跨域么

经理 等级规则
1565/2000
资料完整度
10/100
用户活跃度
0/100

Ta的关注

4

Ta的粉丝

1

Ta的访客

8