symfony 4 redirecttoroute() not working with fetch

115 Views Asked by At

for test if I put directly '/hellotest' it work, redirect! but when I use fetch the Request Attributes are correct, but doesn't redirect. I'm new, what am I missing?:( thanks

/**
 * @Route("/hellotest",name="inde")
 */
public function index()
{
    return $this->redirectToRoute('node', ['id' => 1]);
}

/**
 * @Route("/crec", name="crec",methods={"POST"})
 */
public function crec(SessionInterface $session, Request $request)
{
    $data = $request->request->all();

    return $this->redirectToRoute('node', ['id' => $data['id']]);
}

/**
 * @Route("/node/{id}",name="node")
 */
public function nodeid(SessionInterface $session, $id)
{
    //I do something
}

On Javascript side:

function send(id) {
    const data = new FormData();
    data.append('id', id);

    fetch('/crec', {
        method: 'POST',
        body: data
    })
}
1

There are 1 best solutions below

0
On

Use URLSearchParams on you Javascript, you are trying to use "multipart/form-data" so use "application/x-www-form-urlencoded" instead. Note the code has not been tested.

function send(id) {
    fetch("/crec", {
      method:"POST"
    , body:new URLSearchParams(`id=${id}`)
    })
}