CORS政策问题在React和fetch中。

huangapple go评论77阅读模式
英文:

CORS policy issue in React and fetch

问题

我正在尝试在React TypeScript组件中使用fetch从外部API获取数据,但出现了以下错误:

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.

我的React tsx组件如下:

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;

相同的逻辑在其他不需要授权的API上运行正常,比如 https://jsonplaceholder.typicode.com/todos/1

有任何修复方法吗?
我甚至尝试了最简单的解决方案,即浏览器扩展程序,但它们都没有起作用。

英文:

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

Access to fetch at &#39;https://api.airtable.com/{my_data_base}&#39; from origin 
&#39;http://localhost:3000&#39; 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 &#39;react&#39;;

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

	return &lt;div&gt;Collection Page Component&lt;/div&gt;;
};

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.

答案1

得分: 2

首先,mode 属性不是 headers 对象的一部分,而是属于整个选项对象,就像 herders 一样,其次,你不需要它。 <br>
另外,传递令牌的属性是 Authorization 而不是 Authentication

英文:

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. <br>
Also the property for passing tokens is Authorization not Authentication.

答案2

得分: -1

请检查您的 backend 是否允许您的 frontendcors 白名单中,并且我认为设置模式是不必要的。

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

请注意,上述代码中的注释部分 mode: 'no-cors' 已被注释掉,因为我认为它是不必要的。

英文:

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

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import { FC, useEffect } from &#39;react&#39;;

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

    return &lt;div&gt;Collection Page Component&lt;/div&gt;;
};

export default Collection

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月16日 06:13:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76485826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定