简体   繁体   中英

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.

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 -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. I receive this response:

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

Here is my fos_rest.yaml file:

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

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"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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