[英]Unable to display API data on React frontend
我正在尝试返回从私有 API 获取的数据并将其显示在页面上。 我的前端使用 React JS,我的后端使用带有 Express 和 Axion 的节点。 我的代码一直到返回数据为止。 我得到我的 APi 密钥并获取我的数据,但数据没有传输到我的页面 (Quotes.js)。
后端app.js
import express from "express";
import { getCase } from "./getCase.js";
const app = express();
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.get("/", function (req, res) {
console.log("app.js call getCase");
res.send(getCase());
//console.log(req);
});
//console.log(Quote.getQuote());
let port = process.env.PORT;
if (port == null || port == "") {
port = 5000;
}
app.listen(port, function () {
console.log(`Server started on port ${port}...`);
});
后端getCase
import { getToken } from "./nsApiToken.js";
import axios from "axios";
let getData = "";
console.log("begin of getCase");
const getCase = async () => {
let tokenRes = await getToken();
const url =
"https://5156735-sb1.app.netsuite.com/app/site/hosting/restlet.nl?script=860&deploy=1&recordtype=supportcase&id=717986";
try {
const res = await axios.get(url, {
headers: {
Authorization: `Bearer ${tokenRes.data.access_token}`,
},
});
return res;
} catch (error) {
return error;
}
};
export { getCase };
前端 App.js
import logo from "./logo.svg";
import "./App.css";
import Quotes from "./Quotes.js";
function App() {
return (
<div className="App">
<header className="App-header">
<Quotes />
</header>
</div>
);
}
export default App;
前端 Quotes.js
import React, { useState, useEffect } from "react";
import axios from "axios";
const Quotes = async () => {
const [text, setText] = useState([]);
const [author, setAuthor] = useState("");
const getQuote = await axios
.get("http://localhost:5000", {
crossdomain: true,
})
.then((res) => res.data)
.then((data) => {
setText({
data: data,
});
console.log("res: ", text);
});
return (
<div>
<button onClick={getQuote}>Generate Quote</button>
<h1>{text}</h1>
<h3>{author}</h3>
</div>
);
};
export default Quotes;
过程:当我运行我的过程时,前端在 axios get 过程中执行并调用 Quotes.js。 app.js 然后路由到 home ('/') 并通过 app.get 调用 getCase。 getCase 进程执行获取 API 令牌并将其添加到标头授权中。 该过程启动呼叫并获取数据(如果我 console.log(res.data.fields.phone) 或 console.log(res.data.id) 我看到正确的数据。在我的 Quotes.js 中我想显示数据但 res.data 为空,但我返回状态 200。
我一直在试图理解为什么它没有将数据从后端传递到前端。
有几个问题和一些改进。
AxiosResponse
只需发送数据
const getCase = async () =>
(
await axios.get(
"https://5156735-sb1.app.netsuite.com/app/site/hosting/restlet.nl",
{
params: {
script: 860,
deploy: 1,
recordtype: "supportcase",
id: 717986,
},
headers: {
Authorization: `Bearer ${(await getToken()).data.access_token}`,
},
}
)
).data; // Return the data, not the whole response
你需要等待结果
app.get("/", async (req, res, next) => {
try {
res.json(await getCase());
} catch (err) {
next(err); // send the error to the Express error handler
}
});
当您创建一个综合的 CORS 中间件时,它看起来与标准中间件完全一样,所以只需使用它
import express from "express";
import cors from "cors";
const app = express();
express.use(cors());
Function 组件必须返回一个有效的 JSX 节点。 从Quotes
中删除async
为了通过点击按钮触发getQuote
,它需要是一个 function
// if text is an object, initialise it as one
const [text, setText] = useState({});
const getQuotes = async () => {
try {
// there is no "crossdomain" Axios option
const { data } = await axios.get("http://localhost:5000");
setText({ data });
} catch (err) {
console.error(err.toJSON());
}
};
JSX 无法渲染普通对象,您需要引用可以渲染的属性。
<h1>{text.data?.some?.property}</h1>
不知道您的回复 object 是什么样的,所以这只是一般性建议
这不起作用的原因有两个。 首先, res.data
不是异步的 function。而且因为你在等待,所以你可以直接获取数据。 其次,您需要在useEffect
挂钩中进行 API 调用和 setState ,否则它只会以无限重新渲染的情况结束。 您只需执行以下操作,它就可以工作:
useEffect(() => {
const fetchData = async () => {
const {data} = await axios
.get('http://localhost:5000', {
crossdomain: true
})
setText(data)
}
fetchData()
}, [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.