活动:限时7折!去购买
yii2+vue前后端分离时的跨域问题
5 370 2017-10-30

我前端采用vue,接口采用yii2,这样会有一个跨域问题,例如我提交一个post请求,前端请求的方式是options,导致yii2返回405了呢

  • 5 个回答
  • urlManager配置一下当前请求的路由规则允许options操作试试

  • 我是参照狼哥的restful那篇实战教程写的,现在rules配置如下:

    /**
     * 在这里配置所有的路由规则
     */
    $urlRuleConfigs = [
        [
            'controller' => ['v1/user'],
            'extraPatterns' => [
                'POST login' => 'login',
                'POST logout' => 'logout',
                'POST signup' => 'signup',
                'GET user-info' => 'user-info',
                'GET list' => 'list',
                'OPTIONS create' => 'create',
                'POST create' => 'create',
                'POST add' => 'add',
            ],
        ],
    ]

    访问create时,会返回错误

    ethod Not Allowed. This url can only handle the following request methods: POST

    因为前段访问时先发送options请求,再发送一个post请求,我的login接口就没问题,如果把create改个名字叫add,访问也没问题,就是访问create的时候会报这个错误

  • 检查下最终生效的urlManager配置,是否有被其他配置覆盖

  • 我也有同样的问题,vue请求接口时报了 Failed to load http://xxxxx.xxxxx.top/v1/gov/list: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.50.230:8080' is therefore not allowed access.

  • 一劳永逸的方法是配置nginx允许跨域 add_header "Access-Control-Allow-Origin" ; add_header 'Access-Control-Allow-Credentials' 'true'; add_header "Access-Control-Allow-Methods" ; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X_Requested_With,If-Modified-Since,Cache-Control,Content-Type,Authorization,Content-Disposition' always;

登录 去赚佣金