首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使用FOSRestBundle

无法使用FOSRestBundle
EN

Stack Overflow用户
提问于 2012-05-14 01:30:59
回答 1查看 7.5K关注 0票数 12

我正在尝试使用Symfony2和FOSRestBundle来提出一个REST框架,但我失败得很痛苦。

我做了以下工作:

在我的deps文件中:

代码语言:javascript
复制
[FOSRest]
    git=git://github.com/FriendsOfSymfony/FOSRest.git
    target=fos/FOS/Rest

[FOSRestBundle]
    git=git://github.com/FriendsOfSymfony/FOSRestBundle.git
    target=bundles/FOS/RestBundle

[JMSSerializerBundle]
    git=git://github.com/schmittjoh/JMSSerializerBundle.git
    target=bundles/JMS/SerializerBundle

在我的app/config.yml中

代码语言:javascript
复制
fos_rest:
    view:
        formats:
            rss: true
            xml: false
        templating_formats:
            html: true
        force_redirects:
            html: true
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig


sensio_framework_extra:
    view:
        annotations: false

在我的控制器中:

代码语言:javascript
复制
namespace Rest\WebServiceBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;  


class DefaultController extends Controller
{

    public function indexAction($name)
    {


  $view = View::create()
          ->setStatusCode(200)
          ->setData($name);
        return $this->get('fos_rest.view_handler')->handle($view);


    }
}

当我转到网址:http://local.symfony.com/web/app_dev.php/hello/test

我得到了:

代码语言:javascript
复制
Unable to find template "".
500 Internal Server Error - InvalidArgumentException
2 linked Exceptions: Twig_Error_Loader » Twig_Error_Loader

文档对我来说似乎很混乱,我无法继续。我想要的就是能够将一个数据数组传递给控制器,然后返回一个JSON格式。有人能帮帮忙吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-14 03:15:43

config.ymlformats部分,您必须启用json格式并禁用其他格式,并在路由中将默认的_format值设置为json。e.g

代码语言:javascript
复制
# app/config/config.yml
fos_rest:
    view:
        formats:
            json: true
            rss: false # removing them will also work
            xml: false
#.......

#bundle/routing.yml
route_name:
  pattern: /route
  defaults: { _controller: Bundle:Controller:Method, _format:json }

或者,您可以在控制器中执行以下操作

代码语言:javascript
复制
$view->setFormat('json');

还可以查看文档中给出的示例链接。

票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10573764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档