[英]Angular2 (front) and Yii2 (end) - http.get with option 'Content-Type': 'application/json'
I'va been trying to connect Angular2 sample "Tour of Heroes" as frontend part and Yii2 framework as backend controller in yii2 我一直在尝试将Angular2示例“ Tour of Heroes”作为前端部分并将Yii2框架作为yii2中的后端控制器进行连接
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class HeroesController extends ActiveController
{
public $modelClass = 'app\models\Heroes';
public function behaviors()
{
return
yii\helpers\ArrayHelper::merge(parent::behaviors(), [
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
],
]);
}
}
Result ( http://server.local/heroes ): 结果( http://server.local/heroes ):
<response>
<item>
<id>11</id>
<name>Mr. Nice</name>
<title>князь</title>
</item>
<item>
<id>12</id>
<name>Narco</name>
<title>граф</title>
</item>
<item>
<id>13</id>
<name>Bombasto</name>
<title>барон</title>
</item>
curl H 'Content-Type': 'application/json' ' http://server.local/heroes ' is working quite correctly and I get JSON curl H'Content-Type':'application / json''http ://server.local/heroes '正常工作并且我得到JSON
But I can't receive this in Angular2. 但是我在Angular2中收不到。 http.get with options Content-Type': 'application/json
具有选项Content-Type的http.get':'application / json
export class HeroService {
private headers = new Headers({'Content-Type': 'application/json'});
private options = new RequestOptions({ headers: this.headers});
private heroesUrl ='http://server.local/heroes';// 'app/heroes'; // URL to web api
constructor(private http: Http) { }
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl, this.options
)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
But I get an empty Hero[] 但是我得到了一个空虚的英雄[]
Please read this Yii Response Formatting or using this in your controller 请阅读此Yii响应格式或在您的控制器中使用它
public function behaviors()
{
$behaviors = parent::behaviors();
// add CORS filter
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
'Access-Control-Request-Headers' => ['*'],
],
];
$behaviors['contentNegotiator'] = [
'class' => \yii\filters\ContentNegotiator::className(),
'formats' => [
'application/json' => \yii\web\Response::FORMAT_JSON,
],
];
return $behaviors;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.