Skip to content
Advertisement

CORS problem – Access to fetch at *** from origin *** has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ – PUT request to Firebase

I have CORS problem, I am sending an put request for updating data – posts into Firebase with React:

const submitHandler = e => {
        e.preventDefault();
        const err = validate();
        if(err === false) {
            setFormData(formData)
            const requestOptions = {
                method: 'PUT',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    title: title,
                    url: url,
                    author: author,
                    description: description})
            };
            fetch(`https://blog-d8b04-default-rtdb.europe-west1.firebasedatabase.app/posts/${postName}`, requestOptions)
                .then(response => {response.json(); console.log(response)})
                .then(data => console.log(data));
            setFormData(initialState);
        }
    }

I have this notification error in console

Access to fetch at 'https://blog-d8b04-default-rtdb.europe-west1.firebasedatabase.app/posts/-MX1-Df4t59Y3DnyWUzB' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
EditPost.js:58 PUT https://blog-d8b04-default-rtdb.europe-west1.firebasedatabase.app/posts/-MX1-Df4t59Y3DnyWUzB net::ERR_FAILED

With post request – to add new posts everything is working fine. Has someone solution for this problem?

Advertisement

Answer

If you access your database over HTTPS, you need to access the JSON version of your data by appending .json to your database URL, like this:

fetch(`https://blog-d8b04-default-rtdb.europe-west1.firebasedatabase.app/posts/${postName}.json`, requestOptions)
  .then(response => {response.json(); console.log(response)})
  .then(data => console.log(data));

You should also update your database rules because your database is world readable and writable.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement