我正在尝试向 REED 作业 API 发出请求,但出现错误:TypeError: NetworkError when attempting to fetch resource
。调用是在 React 组件中进行的。 Reed API 声明 You will need to include your api key for all requests in a basic authentication http header as the username, leaving the password empty.
这是让我困惑的部分,我不知道如何以这种方式配置提取。为了帮助解决这个问题,我从 Postman 发送了 API 调用并成功获得了响应。正因为如此,我使用Postman的代码生成功能进行了下面的调用,但不起作用:
var myHeaders = new Headers();
myHeaders.append("Authorization", `${process.env.REACT_APP_REED_KEY}==`);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
fetch("https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
更新:
我已将代码更改为以下内容。不幸的是,我仍然遇到错误。我现在也收到一个新错误:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15. (Reason: CORS preflight response did not succeed).
更新代码:
import { encode } from "base-64";
var myHeaders = new Headers();
myHeaders.append("Authorization", `Basic ${encode(process.env.REACT_APP_REED_KEY)}`);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
fetch("https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));