skip to Main Content

Im trying to fetch data from external api using fetch in react typescript component and having the error:

Access to fetch at ‘https://api.airtable.com/{my_data_base}’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Request header field authentication is not allowed by Access-Control-Allow-Headers in preflight response.

My React tsx component is:

import { FC, useEffect } from 'react';

const Collection: FC = () => {
    useEffect(() => {
        fetch('https://api.airtable.com/v0/my_data_base', {
            headers: {
                mode: 'no-cors',
                Authentication: 'Bearer my_token',
            },
        })
            .then((resp) => resp.json())
            .then((data) => {
                console.log(data);
            });
    }, []);

    return <div>Collection Page Component</div>;
};

export default Collection

The same logic works fine with other apis, that don’t require authorisation, like for example https://jsonplaceholder.typicode.com/todos/1

Any idea how to fix it?
I’ve tried even the most stupid solution which is browser extensions but non of them worked.

2

Answers


  1. Check that your backend is allowing the your frontend in cors whitelist, and i think that setting the mode is unnecessary.

    import { FC, useEffect } from 'react';
    
    const Collection: FC = () => {
        useEffect(() => {
            fetch('https://api.airtable.com/v0/my_data_base', {
                headers: {
                    //mode: 'no-cors',
                    Authentication: 'Bearer my_token',
                },
            })
                .then((resp) => resp.json())
                .then((data) => {
                    console.log(data);
                });
        }, []);
    
        return <div>Collection Page Component</div>;
    };
    
    export default Collection
    Login or Signup to reply.
  2. First, the mode property is not part of the headers object but it belongs to the entier options object just like herders, second you don’t need it.
    Also the property for passing tokens is Authorization not Authentication.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search