簡體   English   中英

Angular2(前)和Yii2(結束)-具有選項'Content-Type'的http.get:'application / json'

[英]Angular2 (front) and Yii2 (end) - http.get with option 'Content-Type': 'application/json'

我一直在嘗試將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(),
            ],
        ]);
    }
}

結果( 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 '正常工作並且我得到JSON

但是我在Angular2中收不到。 具有選項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);
  }

但是我得到了一個空虛的英雄[]

請閱讀此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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM