繁体   English   中英

为什么Yii2休息控制器以XML格式给出响应?

[英]Why is Yii2 rest controller giving response in XML format?

目前我在我的api模块上使用以下初始化代码

public function init()
{
    parent::init();
    Yii::$app->response->format = Response::FORMAT_JSON;
}

我的api在以下示例中以XML格式返回响应。

public function actionTest()
{
    $items = ['one', 'two', 'three' => ['a', 'b', 'c']];
    return $items;
}

这是回应:

<response>
  <item>one</item>
  <item>two</item>
   <three>
    <item>a</item>
    <item>b</item>
    <item>c</item>
   </three>
</response>

我能让它工作的唯一方法是在每个控制器行为中添加这一行。 我已经阅读了文档,其中说我可以在模块类中进行此操作,因此我不需要在每个控制器中执行此操作。 我不知道为什么它会提供XML。 另外 ,以防唯一的方法是将它添加到我的行为,我是否必须编写代码来处理名称,代码,状态,类型,以前和代码或Yii提供yii \\ rest \\ Controller和yii \\ rest \\ ActiveController哪个自动处理这个。 很明显,当出现错误时,它们会自动输出。

{"name":"Not Found"
 "message":"Page not found.",
 "code":0,
 "status":404
 "type":"yii\\web\\NotFoundHttpException"
 "previous":{"name":"Invalid Route","message":"Unable to resolve the request: api/home/",
 "code":0,"type":"yii\\base\\InvalidRouteException"
 }
}

经过三个痛苦的日子,我找到了解决方案。 当你来自ExpressJS和NodeJS的整个JSON世界时,有时很难解释这个问题。 从逻辑上讲,Yii2的功能非常好,另一方面90%的RESTful API希望输出为JSON,因此每次进行API调用时都不需要设置请求标头。

浏览器默认将请求标头添加为“Application / XML”,因此您在屏幕上看到的是XML而不是JSON。

收到标题后,Yii2的内容协商员将应用程序/ xml格式化为XML格式的输出。 如果您使用带有标题为“Application / JSON”的CURL或PostMan发出相同的请求,您将获得所需的输出。

如果您希望覆盖此行为,只需在控制器中添加以下功能并包含以下内容: -

使用yii \\ web \\ Response; 使用yii \\ helpers \\ ArrayHelper;

 public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ [ 'class' => 'yii\\filters\\ContentNegotiator', 'only' => ['view', 'index'], // in a controller // if in a module, use the following IDs for user actions // 'only' => ['user/view', 'user/index'] 'formats' => [ 'application/json' => Response::FORMAT_JSON, ], 'languages' => [ 'en', 'de', ], ], ]); } 

我测试你的代码,它的工作完美

我的控制器:

<?php

namespace backend\controllers;


use yii\rest\Controller;
use yii;
use yii\web\Response;

class TestController extends Controller{

    public function init()
    {
        parent::init();
        Yii::$app->response->format = Response::FORMAT_JSON;
    }

    public function actionTest(){
        $items = ['one', 'two', 'three' => ['a', 'b', 'c']];
        return $items;
    }
}

输出:

{"0":"one","1":"two","three":["a","b","c"]}

检查您的命名空间或发送您的代码!

在Yii2应用程序中,默认响应类型是XML(我猜它也是REST的默认值)。 在HTTP连接期间,双方都声明能够发送和/或接收的数据类型。 如果此信息未传递给服务器,则发送默认数据类型(即使您指定应在应用程序中使用JSON)以保证正确的通信。 如果要接收JSON数据,则必须在您的请求中添加Accept: application/json标头。 并且您可能不必在php代码中指定它,因为Yii2应该从请求标头中扣除它。

你可以在这里找到更多解释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM