I'va been trying to connect Angular2 sample "Tour of Heroes" as frontend part and Yii2 framework as backend controller in 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 ):
<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
But I can't receive this in Angular2. http.get with options Content-Type': '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
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.