【问题标题】:Angular2 (front) and Yii2 (end) - http.get with option 'Content-Type': 'application/json'Angular2 (front) 和 Yii2 (end) - http.get with option 'Content-Type': 'application/json'
【发布时间】:2016-10-16 21:55:12
【问题描述】:

我一直在尝试将 Angular2 示例“英雄之旅”连接为前端部分,将 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 中接收到这个。 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);
  }

但我得到一个空英雄[]

【问题讨论】:

  • 浏览器控制台中显示的任何错误?您是否还可以检查请求是否已从开发工具的网络选项卡正确发送?
  • Chrome 控制台中没有错误

标签: json xml angular yii2


【解决方案1】:

请阅读此Yii Response Formatting 或在您的控制器中使用此

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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-23
    • 2020-11-14
    • 1970-01-01
    • 2016-10-02
    • 2015-02-01
    • 2015-10-20
    • 2018-03-17
    • 2015-08-30
    相关资源
    最近更新 更多