Axios put request and symfony controller

Viewed 2132

Can you explain me why Axios request does not work in my Symfony application?

I use Axios request with React like this :

handleSubmit = () => {
    axios.put('/families/' + this.props.familyId + '/edit',{
        parents: "test"
    })
        .then(response => {
            alert('Family has been modified');
        })
};

My controller :

/**
 * Edit Family
 *
 * @Route("families/{id}/edit", name="family_edit")
 * @Method(methods={"PUT"})
 * @param Request $request
 * @param $id
 */
public function editFamilyAction(Request $request, $id)
{
    $parents = $request->get('parents');

    ...
}

But $parents equals null...

What is happening, do I need some configuration somewhere?

Help needed please!

Denis

2 Answers

It's simple as that:

/**
 * @Route("/families/{id}/edit", name="family_edit", methods={"PUT"})
 * @param Request $request
 * @param $id
 */
public function editFamilyAction(Request $request, $id)
{

    $data = $request->getContent();
    $data = json_decode($data);
    $parents = $data->parents;

    // do your stuff
}

Note that if you are using Symfony 4, Method annotation has been deprecated, instead you should configure the Route annotation properly like I did in the code above.

Wow it seems that it is working ! thanks you very very much guy!!

Can you explain me what is my mistake please?

I have just copy/pasted team code without success. Let me explain the code :

React :

 handleSaveDiagnostic = () => {
    axios.put('/admin/api/diagnostic/update-diagnostic/'+ this.state.currentDiagnostic.id, {
        'newDiagnostic': this.state.currentDiagnostic
    })
        .then(response => {
            alert('Family has been modified');
            this.loadCounters();
        })
};

Controller :

* @Route("/update-diagnostic/{diagnostic}", name="update_diagnostic")
 * @Method(methods={"PUT"})
 *
 * @param \Symfony\Component\HttpFoundation\Request $request
 * @param \AppBundle\Entity\Diagnostic $diagnostic
 *
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function updateDiagnosticAction(Request $request, Diagnostic $diagnostic) {

    $newDiagnostic = $request->get('newDiagnostic'); (is working!)

    ...
}

What's the difference please, it is working for him but $request->getContent is needed for me??!!

Related