【问题标题】:API Fetch Cross-Orgin RequestAPI Fetch 跨域请求
【发布时间】:2021-07-18 17:43:43
【问题描述】:

我正在尝试将 GitHub 作业 API 用于 React 应用程序。我正在尝试使用 useEffect 和 fetch 来检索数据,但出现错误。

我得到的错误如下:

错误 1:跨域请求被阻止:同源策略不允许读取位于 https://jobs.github.com/positions.json 的远程资源。 (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。

错误 2: Uncaught (in promise) TypeError: NetworkError when trying to fetch resource.

我查看了文档,但无法确定错误是什么。

UseFetch.js

import { useState, useCallback, useEffect } from "react";

const SearchAll = () => {

    const [jobs, SetJobs] = useState(null)

    const url = "https://jobs.github.com/positions.json";

    useEffect (() => {
        
        fetch(url)
        .then(res => {
            if (!res.ok) { 
              throw Error('could not fetch the data for that resource');
            } 
            return res.json();
          })
          .then(data => {
            SetJobs(data);
          })
    },[url])

【问题讨论】:

    标签: reactjs fetch use-effect


    【解决方案1】:

    CORS 错误表示服务器尚未将您的域列入白名单,这是在浏览器中实施的一种安全机制。没错 - 您尝试访问的 API 属于 github.com。您必须通过它构建 HTTP 服务器和代理响应。

    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 1970-01-01
      • 2013-09-12
      • 2023-03-21
      • 2015-06-22
      • 2015-01-26
      • 2017-06-15
      相关资源
      最近更新 更多