[英]How to get API data from node js to display on React
我正在學習 react 和 node js,我正在制作一個宏計算器網站,基本上我從客戶端的用戶那里獲取數據(卡路里、宏比率等),然后使用這些數據向 edamam API 發出獲取請求服務器獲取(foodID,uri,unit)並再次發布這些數據以獲取每種食物的宏。 然后我計算了數據。 (到目前為止,它在后端工作正常)。 我想將此數據發送回前端以顯示,但它在這里不起作用。 我正在使用 axios 來處理請求。 我也不太確定進行 API 調用的正確方法。 任何幫助將不勝感激謝謝
從 React 向后端發送數據
async function postData(e){
e.preventDefault();
try{
await axios.post("http://localhost:4000/getData", {formData})
}
catch(error){
console.log(error.response.data);
}
}
Node.js 進行 API 調用和處理數據
app.post("/getData", (req, res) =>{
// data from React
const targetKcal = req.body.formData.calories;
const proteinRatio = req.body.formData.proteinRatio;
const fatRatio = req.body.formData.fatRatio;
const carbRatio = req.body.formData.carbRatio;
const proteinSource = req.body.formData.proteinSource;
const fatSource = req.body.formData.fatSource;
const carbSource = req.body.formData.carbSource;
const getURL = "https://api.edamam.com/api/food-database/v2/parser?";
const postURL = "https://api.edamam.com/api/food-database/v2/nutrients?";
//GET Request to parse and get uri and foodID to post
try{
Promise.all([
axios.get(getURL, {params :{"ingr" : proteinSource}}),
axios.get(getURL, {params :{"ingr" : fatSource}}),
axios.get(getURL, {params :{"ingr" : carbSource}}),
]).then(axios.spread((proteinData, fatData, carbData) => {
try{
//post data to get macro info for each macros
Promise.all([
axios.post(postURL, {"ingredients" :[{"quantity":1, "measureURI": proteinData.data.hints[0].measures.filter(obj => obj["label"] === "Gram")[0].uri,"foodId":proteinData.data.parsed[0].food.foodId}]}),
axios.post(postURL, {"ingredients" :[{"quantity":1, "measureURI": fatData.data.hints[0].measures.filter(obj => obj["label"] === "Gram")[0].uri,"foodId":fatData.data.parsed[0].food.foodId}]}),
axios.post(postURL, {"ingredients" :[{"quantity":1, "measureURI": carbData.data.hints[0].measures.filter(obj => obj["label"] === "Gram")[0].uri,"foodId":carbData.data.parsed[0].food.foodId}]})
]).then(axios.spread((data1, data2, data3) => {
let proteinKcal = data1.data.totalNutrients.ENERC_KCAL.quantity;
let protein = data1.data.totalNutrients.PROCNT.quantity;
let proteinFat = data1.data.totalNutrients.FAT.quantity;
let proteinCarb = data1.data.totalNutrients.CHOCDF.quantity;
let fatKcal = data2.data.totalNutrients.ENERC_KCAL.quantity;
let fatProtein = data2.data.totalNutrients.PROCNT.quantity;
let fat = data2.data.totalNutrients.FAT.quantity;
let fatCarb = data2.data.totalNutrients.CHOCDF.quantity;
let carbKcal = data3.data.totalNutrients.ENERC_KCAL.quantity;
let carbProtein = data3.data.totalNutrients.PROCNT.quantity;
let carbFat = data3.data.totalNutrients.FAT.quantity;
let carb = data3.data.totalNutrients.CHOCDF.quantity;
//Calculate each macros for target calories
const proteinTargetGram = (targetKcal * (proteinRatio / 100))/proteinKcal;
const fatTargetGram = (targetKcal * (fatRatio / 100))/fatKcal;
const carbTargetGram = (targetKcal * (carbRatio / 100))/carbKcal;
proteinKcal *= proteinTargetGram;
protein *= proteinTargetGram;
proteinFat *= proteinTargetGram;
proteinCarb *= proteinTargetGram;
fatKcal *= fatTargetGram;
fatProtein *= proteinTargetGram;
fat *= fatTargetGram;
fatCarb *= proteinTargetGram;
carbKcal *=carbTargetGram;
carbProtein *= proteinTargetGram;
carbFat *= proteinTargetGram;
carb *= carbTargetGram;
const totalKcal = (proteinKcal + fatKcal + carbKcal).toFixed(0);
const totalProtein = (protein + fatProtein + carbProtein).toFixed(0);
const totalFat = (proteinFat + fat + carbFat).toFixed(0);
const totalCarb = (proteinCarb + fatCarb + carb).toFixed(0);
const data = {
"totalKcal": totalKcal,
"totalProtein": totalProtein,
"totalFat": totalFat,
"totalCarb": totalCarb,
"proteinTargetGram": proteinTargetGram,
"fatTargetGram": fatTargetGram,
"carbTargetGram":carbTargetGram
};
//send back the data
res.json(data);
}))
}catch(err) { console.log(err); }
}));
}
catch (err) { console.error(err); }
});
使用數據在 React 上顯示
function Result() {
const [data, setData] = useState([]);
useEffect(()=>{
const getData = async ()=> {
const response = await axios.get('/getData');
setData(response.data);
};
getData();
});
return (
<div>
<h1>{data.map(item => item)}</h1>
</div>
)
}
export default Result
錯誤信息
- - - - - - - - - - - -編輯 - - - - - - - - - - - - - -----------------
我在下面添加了 res.json(data) 而不是 res.json(data)
axios.post('/getData', data)
.then(res => console.log(res.json))
.catch(err => console.log(err.json));
反應時顯示
function Result() {
const [data, setData] = useState([]);
useEffect(()=>{
const getData = async ()=> {
const response = await axios.get('http://localhost:4000/getData');
setData(response.data);
};
getData();
});
return (
<div>
<h1>{Object.keys(data).map(key => data[key])}</h1>
</div>
)
}
我仍然收到錯誤
生成錯誤是因為您要求后端不存在的 GET 方法,這就是您在那里看到 404 的原因。 您實際上有一個 POST 聲明(getData),您應該通過在主體上傳遞值來請求 POST 方法。 像這樣的東西:
axios.post('/getData', {
// pass the formData here
formData:{
// calories: ...,
// ...
}
})
.then(function (response) {
// update state
})
.catch(function (error) {
// handle error
});
Axios 很好,如果您不想使用外部 package 可以使用 fetch。 您可以在此處找到文檔。
對於渲染:你必須做一些不同的事情,因為你收到一個 object 你應該在鍵上 map ,改變這個:
<h1>{data.map(item => item)}</h1>
像這樣:
<h1>{Object.keys(data).map(key => key + ": " + data[key])}</h1>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.