Yii restful api跨域

Posted 岁月如歌

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Yii restful api跨域相关的知识,希望对你有一定的参考价值。

问题: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跨域的主要内容,如果未能解决你的问题,请参考以下文章

使用 RESTful 服务保护跨域的 API 调用

Yii2框架RESTful API教程

使用令牌实现 RESTful API 身份验证 (Yii/Yii2)

yii2 RESTful api的详细使用

Yii2框架RESTful API教程 - 快速入门

Yii2 使用 RESTful 写API接口 实例