2018-05-09 10:40:59 3455次浏览 1条回答 3 悬赏 200 金钱

QQ图片20180509103824.png
QQ图片20180509103833.png

接口开发测试时,使用POSTMAN等接口调试工具没有问题,但是前段访问时出现这种跨域问题,代码中已经设置了跨域的过滤器,为什么还是不好用,需要在NGINX服务器上也做配置么

前段框架用到了vue2

因为Yii2+vue2 他回碰到常规问题就是cors 与 auth AUTH与cors有先后问题。还有看options你直接查看auth下的optionAction,CORS知识面有点广。不是一两句可以说清,你追踪YII的处理方式

补充于 2018-05-09 13:38

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

补充于 2018-05-09 14:34

在开发文档上找到了,当初是英文写的也就没特意的注意,现在发现真是恼火,浪费了半天时间找原因。
以下是原文
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

  • 回答于 2018-05-09 13:58 举报

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

    1 条回复
    回复于 2018-05-09 14:29 回复

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

您需要登录后才可以回答。登录 | 立即注册
hp66722667
经理

hp66722667

注册时间:2018-01-26
最后登录:2020-02-26
在线时长:23小时1分
  • 粉丝1
  • 金钱1335
  • 威望0
  • 积分1565

热门问题