Symfony React Cors issue

I use Symfony 5 and React, with docker, and both are on the same network.

Now I want to POST something on one of my api route, here is my request:

const handleSubmit = async function (e) {
        setError(null)
        setLoading(true)
        e.preventDefault()
        const data = new FormData(e.target)
        console.warn(data)
        try {
            const response = await fetch('https://localhost:8443/authentication_token', {
                credentials: 'include',
                headers: {
                    Accept: 'application/json',
                },
                method: 'POST',
                body: data,
            })

            console.warn(response)
            const responseData = await response.json()
            console.warn(responseData)
            onConnect(responseData)
        } catch (e) {
            setError(e)
            setLoading(false)
        }
    }

Then I’m getting the following error:

Access to fetch at 'https://localhost:8443/authentication_token' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

So after some search I installed nelmio package to deal with cors, here is my nelmio_cors.yml file:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
        forced_allow_origin_value: ~
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['Content-Type', 'Authorization']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
        '^/':
            origin_regex: true
            allow_origin: ['^http://localhost:[0-9]+']
            allow_headers: ['Content-Type', 'Authorization']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
            hosts: ['^api.']

And added the below line in my .env:

###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN=CORS_ALLOW_ORIGIN=^https?://.*?$
###< nelmio/cors-bundle ###

And yet I get the same error and didn’t manage to find an answer online.

Does anyone see what I’ve done wrong?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *