【问题标题】:React hooks useEffect fetch CORS issueReact hooks useEffect fetch CORS 问题
【发布时间】:2021-06-29 02:15:07
【问题描述】:

我很难找到有关在此 try/catch 块中放置 CORS 标头的位置的信息。

例如:模式:'no-cors'

useEffect(() => {

  const fetchData = async() => {
    try {
      setLoading(true);
      const response = await fetch('http://[::1]:3000/users');
      const json = await response.json();
      setData(json.results, setLoading(false));
    } catch(err) {
      console.warn('API Error:', err);
      setLoading(false);
    }
  }

  if(amount) {
    fetchData(amount);
  }
}, [amount])

我是 hooks 的新手,如果有任何关于与后端通信的建议或改进,我将不胜感激。

非常感谢:)

【问题讨论】:

    标签: reactjs api react-hooks cors


    【解决方案1】:

    fetch() 方法可以选择接受第二个参数,它允许您控制许多不同的设置:

    useEffect(() => {
            const fetchData = async() => {
                try {
                    setLoading(true);
                    const response = await fetch('http://[::1]:3000/users', {
                        method: 'POST', // *GET, POST, PUT, DELETE, etc.
                        mode: 'cors', // no-cors, *cors, same-origin
                        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
                        credentials: 'same-origin', // include, *same-origin, omit
                        headers: {
                            'Content-Type': 'application/json'
                            // 'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        redirect: 'follow', // manual, *follow, error
                        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
                        body: JSON.stringify(data) // body data type must match "Content-Type" header
                    });
                    const json = await response.json();
                    setData(json.results, setLoading(false));
                } catch(err) {
                    console.warn('API Error:', err);
                    setLoading(false);
                }
            };
    
            if(amount) {
                fetchData(amount);
            }
        }, [amount]);
    

    查看FetchAPI 文档了解更多详情。

    【讨论】:

      猜你喜欢
      • 2021-03-30
      • 1970-01-01
      • 2020-11-28
      • 2023-01-14
      • 2020-01-24
      • 2020-09-10
      • 2017-07-26
      • 2020-03-23
      • 2020-06-08
      相关资源
      最近更新 更多