3

I am trying to send post data using fetch in twig. But I can not access to those variables in the controller.

here my fetch


let response = await fetch(baseUrl + '/aaa/nom-de-levenement/add', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': token,
            "Content-type": "application/json",
        },

        body: {
            "page": "pageName"
        }
    })
    return response.json()

and my controller :


/**
     * @Route("/add", methods={"POST"})
     */
    public function createPage($slug, EntityManagerInterface $entityManager, EventRepository $eventRepository, Request $request){

        $event = $eventRepository->findOneBy(['slug' => $slug]);

        $data = $request->request->get('page');

        dd($data);
}

And the dump returning null

Thank you for help

I tryied to change the content type in fetch dans some things in the controller for exemple :

$_POST return null

$request->get('page') return null

I try the controller using postman, and it return the good variable.

victorfau
  • 45
  • 1
  • 4
  • 18
  • try to send body as a string in fetch API: `body : JSON.stringfy({page: "pageName"})`. One more point I think you have to adjust the route annotation and include a `slug` there: `@Route("/{slug}/add", methods={"POST"})`. And then try `$request->request->get('page', 'default page')` – Jumshud Jul 09 '20 at 11:25
  • Hello thank you for your help. Firstly, slug in configure for the controller in global. I tryied to stringfy the body but I always get the default result. – victorfau Jul 09 '20 at 12:47
  • What if you update Content-Type to `application/x-www-form-urlencoded` ? – Jumshud Jul 09 '20 at 12:52
  • This gave me an anwer : ``$this->request->request->all()`` give me : ``` { "page: myPage" : null } ``` – victorfau Jul 09 '20 at 15:39

1 Answers1

5

To send POST data that way you should use FormData object:

const data = new FormData();
data.append('page', 'pageName');

let response = await fetch(baseUrl + '/aaa/nom-de-levenement/add', {
    method: 'POST',
    headers: {
        'X-CSRF-TOKEN': token,
        "Content-type": "application/json",
    },
    body: data
})
return response.json()

Then you could do that in your controller:

$data = $request->request->get('page');

If you try to pass "raw" data in body, you can access it using $request->getContent() method, but I believe in this case that will return "[object Object]" because the body object will be simply parsed to string.

wjatek
  • 922
  • 7
  • 22