【发布时间】:2017-08-08 18:19:46
【问题描述】:
我正在制作 Angular 2 / Yii2 应用程序
当我使用不记名标头从 Postman 调用自定义控制器/操作时,一切正常,但是当我使用 angular 2 应用程序 (localhost:4200) 中的相同标头调用它时,我总是收到未经授权的 401 错误。 当我从guide 的示例中执行标准操作时,例如:
GET /users: list all users page by page;
POST /users: create a new user;
一切正常,只有当我创建自定义操作时,才会获得未经授权。
这是跨域应用, angular 可在 web.example.com 上找到, yii2 应用在 srv.example.com 上
namespace app\controllers\restapi;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
class SearchOrderController extends \yii\rest\Controller
{
public $modelClass = 'app\models\Order';
public function behaviors()
{
$behaviors = parent::behaviors();
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
];
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBearerAuth::className(),
],
];
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
return $behaviors;
}
public function actionSearch(){
\Yii::$app->response->format=\yii\web\Response::FORMAT_JSON;
return ['index'=>'some text', 'value'=>123];
}
}
也是我的网址管理器:
[
'class' => 'yii\rest\UrlRule',
'controller' => 'order',
'pluralize' => false,
'extraPatterns' => [
'GET order/<id:\id+>' => 'order/view',
]
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'search-order',
'pluralize' => false,
'extraPatterns' => [
'GET search-order/search' => 'search-order/search',
]
【问题讨论】:
-
你确定 GET 和 POST 是失败的请求吗?您能否检查一下您浏览器的网络选项卡,看看它是否不是失败的
OPTIONS /users? -
这是选项...因为我收到的消息是:选项srv.example.com/restapi/search-order/search 401(未经授权)我该怎么办?