我正在使用Yii2开发一个rest API,前端是由ionic开发的。 这种情况是,当我有一个使用承载认证的动作时.. 它工作正常,但访问令牌与响应主体一起返回,导致客户端的HttpErrorResponse:
SyntaxError: Unexpected token y in JSON at position 0 at Json.parse
响应会像这样返回,因此客户端无法解析json
y2sSCEXqkUoVY2BjkQZqx8g3W42273Cz{"success":false,"message":"you liked it before"}
这是使用bearear身份验证的行为代码
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => CorsCustom::className(),
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'only' => ['like', 'unlike', 'likes', 'create'],
'authMethods' => [
HttpBearerAuth::className(),
],
];
return $behaviors;
}
我想停止在正文中发送访问令牌或将其作为json发送
答案 0 :(得分:3)
在回复之前停止echo
令牌,您将完成工作!
public static function findIdentityByAccessToken($token, $type = null)
{
/* echo $token; */
return static::findOne(['auth_key' => $token]);
}
答案 1 :(得分:3)
我认为您应该从USER模型中删除echo $token
语句
public static function findIdentityByAccessToken($token, $type = null)
{
/* echo $token; */
return static::findOne(['auth_key' => $token]);
}