【发布时间】: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