简体   繁体   English

Symfony FOSRestBundle API - 接收空的 JSON 请求正文

[英]Symfony FOSRestBundle API - receives empty JSON Request body

I'm trying to build Symfony API with the bundle, but every request that I sent has empty body.我正在尝试使用捆绑包构建 Symfony API,但我发送的每个请求都有空正文。

Controller: Controller:

class IndexController extends AbstractFOSRestController
{
    /**
     * @Rest\Post("/api/test", methods={"POST"})
     * @param Request $request
     * @return View
     */
    public function testError(
        Request $request
    ) : View {

        $requestData = $request->request->all(); // problem: requestData is []

        return View::create()
            ->setStatusCode(200)
            ->setFormat("json")
            ->setData(["data" => $requestData, "status" => "ok"]);
    }
}

I am sending this request from CURL:我从 CURL 发送此请求:

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:8000/api/test

I've also tried sending it with Postman.我也试过用 Postman 发送它。 I receive this response:我收到以下回复:

{"data":[],"status":"ok"}

Here is my fos_rest.yaml file:这是我的 fos_rest.yaml 文件:

fos_rest:
    view:
        view_response_listener: true
    format_listener:
        rules:
            - { path: ^/api, prefer_extension: true, fallback_format: json, priorities: [ json, html ] }
            - { path: ^/, prefer_extension: true, fallback_format: json, priorities: [ html, json ] }

I think you forgot about proper serializer, which is mostly required.我认为您忘记了正确的序列化程序,这主要是必需的。 Here is my config, should help you with it:这是我的配置,应该可以帮助您:

fos_rest:
    serializer:
        serialize_null: true
    body_listener:
        enabled: true
        throw_exception_on_unsupported_content_type:  true
        decoders:
            json: fos_rest.decoder.json
    format_listener:
        rules:
            - { path: '^/api', priorities: ['json'], fallback_format: json, prefer_extension: false }
            - { path: '^/', priorities: ['html', '*/*'], fallback_format: html, prefer_extension: true }
    param_fetcher_listener: force
    view:
        view_response_listener: 'force'
        formats:
            json: true
    allowed_methods_listener: true
services:
    fos_rest.decoder.json:
        class: FOS\RestBundle\Decoder\JsonDecoder
        public: true

Manual手动的

Symfony: Setting up the bundle, part B Symfony:设置捆绑包,B 部分

Edit: One way to fix it is the accepted answer, the other is the below code编辑:修复它的一种方法是接受的答案,另一种是下面的代码

$requestData = json_decode($request->getContent(), true);

return View::create()
        ->setStatusCode(200)
        ->setFormat("json")
        ->setData(["data" => $requestData, "status" => "ok"]);

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

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