React.js:使用 Bearer Token 从 API 获取数据
React.js: Fetching Data from API with Bearer Token
我正在构建一个 React.js SPA,它使用 Bearer Token 身份验证从 API 接收数据(因此必须先完成身份验证的提取请求,并且可以临时使用给定的令牌在身份验证会话结束之前访问数据)
我可以授权对象并将其打印到控制台,但该对象未保存到变量 objectOutput 中以便下面的组件访问。
我的想法是,异步获取导致了这种情况,组件在 fetch() 结果到达之前呈现。但我想知道如何解决这个问题,所以我可以将它存储在变量中,并且组件可以访问数据作为它们的道具。
import Header from "./components/Header";
import Cardsection from "./components/Cardsection";
import Flagsection from "./components/Flagsection";
import Footer from "./components/Footer";
import MapChart from "./components/MapChart";
import { useEffect } from "react";
let api_url = "https://api-url:3000";
let batch_id = "XXX";
let api_token = "";
let objectOutput = "";
function App() {
useEffect(() => {
const authorize = async () => {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
username: "username",
password: "password",
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow"
};
const res = await fetch(api_url + "/auth", requestOptions).catch(console.log("error"));
const data = await res.json();
api_token = data.token;
console.log("Successful Authorization. Token: " + api_token);
const getObject = async () => {
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + api_token);
var requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow"
};
const res = await fetch(api_url + "/get?function=readObject&args=" + batch_id, requestOptions).catch(console.log("error"));
const data = await res.json();
objectOutput = data;
console.log(data);
};
getObject()
};
authorize();
}, []);
return (
<div className="App">
<Header
title="Lorem Ipsum"
description="Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
/>
<Flagsection hasFlag={objectOutput.alarmFlag} />
<Cardsection sort={""} treatment={""} plantheight={""} harvesttime={""} />
<MapChart/>
<Footer />
</div>
);
}
export default App;```
这将帮助您解决问题,因为您没有使用 useState
钩子
function App() {
const [objectOutput, setObjectOutput] = useState();
useEffect(() => {
const authorize = async () => {
const res = await fetch(api_url + "/auth", requestOptions).catch(console.log("error"));
const data = await res.json();
api_token = data.token;
const getObject = async () => {
const res = await fetch(api_url + "/get?function=readObject&args=" + batch_id, requestOptions).catch(console.log("error"));
const data = await res.json();
objectOutput = data;
// add below line to set object
setObjectOutput(data);
};
getObject()
};
authorize();
}, []);
如果要更改,则使用此 dependency
、
重新渲染
useEffect(() => {}, [objectOutput]);
我正在构建一个 React.js SPA,它使用 Bearer Token 身份验证从 API 接收数据(因此必须先完成身份验证的提取请求,并且可以临时使用给定的令牌在身份验证会话结束之前访问数据)
我可以授权对象并将其打印到控制台,但该对象未保存到变量 objectOutput 中以便下面的组件访问。
我的想法是,异步获取导致了这种情况,组件在 fetch() 结果到达之前呈现。但我想知道如何解决这个问题,所以我可以将它存储在变量中,并且组件可以访问数据作为它们的道具。
import Header from "./components/Header";
import Cardsection from "./components/Cardsection";
import Flagsection from "./components/Flagsection";
import Footer from "./components/Footer";
import MapChart from "./components/MapChart";
import { useEffect } from "react";
let api_url = "https://api-url:3000";
let batch_id = "XXX";
let api_token = "";
let objectOutput = "";
function App() {
useEffect(() => {
const authorize = async () => {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
username: "username",
password: "password",
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow"
};
const res = await fetch(api_url + "/auth", requestOptions).catch(console.log("error"));
const data = await res.json();
api_token = data.token;
console.log("Successful Authorization. Token: " + api_token);
const getObject = async () => {
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + api_token);
var requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow"
};
const res = await fetch(api_url + "/get?function=readObject&args=" + batch_id, requestOptions).catch(console.log("error"));
const data = await res.json();
objectOutput = data;
console.log(data);
};
getObject()
};
authorize();
}, []);
return (
<div className="App">
<Header
title="Lorem Ipsum"
description="Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
/>
<Flagsection hasFlag={objectOutput.alarmFlag} />
<Cardsection sort={""} treatment={""} plantheight={""} harvesttime={""} />
<MapChart/>
<Footer />
</div>
);
}
export default App;```
这将帮助您解决问题,因为您没有使用 useState
钩子
function App() {
const [objectOutput, setObjectOutput] = useState();
useEffect(() => {
const authorize = async () => {
const res = await fetch(api_url + "/auth", requestOptions).catch(console.log("error"));
const data = await res.json();
api_token = data.token;
const getObject = async () => {
const res = await fetch(api_url + "/get?function=readObject&args=" + batch_id, requestOptions).catch(console.log("error"));
const data = await res.json();
objectOutput = data;
// add below line to set object
setObjectOutput(data);
};
getObject()
};
authorize();
}, []);
如果要更改,则使用此 dependency
、
useEffect(() => {}, [objectOutput]);