Can’t fetch data to Symfony API from React+Formik

  fetch, formik, php, symfony

i’m new on React/symfony and i try to build a React App connected to an API i created with Symfony.

I can fetch data from the API to show them on a main page, but on my registration form (built with Formik), i can’t send data on submit.

I got a 500 internal server error.

Unfortunately i have nothing on the error.log but i have an error on symfony : No route found for "GET localhost:8000/api/signup": Method Not Allowed (Allow: POST)

I already tried to check some parameters, even on Nelmio but POST methods seems allowed everywere

Here the Formik code :

const RegisterBox = () => {

    const formik = useFormik({
        initialValues: {
            email: '',
            pseudo: '',
            nom: '',
            password: ''
        },
        validationSchema: Yup.object({
            email: Yup.string().email('Adresse mail invalide').required('* obligatoire'),
            pseudo: Yup.string().required('* obligatoire'),
            nom: Yup.string(),
            prenom: Yup.string(),
            password: Yup.string()

                .min(8, 'Mot de passe trop court (8 mini)')
                .required('* obligatoire'),
            passwordConf: Yup.string()
                .min(8, 'Mot de passe trop court (8 mini)')
                .oneOf([Yup.ref('password'), null], 'Les mots de passes doivent être identiques')
                .required('* obligatoire'),

            // http://127.0.0.1:8000/api/signup
        }),
        onSubmit: async (values) => {

            const response = await fetch(`http://localhost:8000/api/signup`, {
                method: 'POST',
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ values })
            }).then(response => response.json())
                .then(responseJson => {
                    console.log(responseJson);
                })
        }
    })

And the symfony controller :


header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");

...

 #[Route('/api/signup', name: 'api_signup_index', methods: ["POST"])]

    public function signup(Request $request, SerializerInterface $serializer, EntityManagerInterface $em, UserPasswordHasherInterface $passwordHasher, UserRepository $userRepository): Response
    {
        $this->passwordHasher = $passwordHasher;
        $jsonpost = $request->getContent();
        $user = $serializer->deserialize($jsonpost, USER::class, 'json');
        $user->setCreatedAt(new DateTimeImmutable());
        $user->setRoles(["ROLE_USER"]);
        $user->setPassword($this->passwordHasher->hashPassword($user, true));
        $em->persist($user);
        $em->flush();

        dd($user);

        return $this->json($userRepository->findOne($user), 200, []);

before this error, i got CORS issues but seems resolved with nelmio cors

Thanks !

Source: Symfony Questions

LEAVE A COMMENT