如何将唯一标识符从我的快速后端服务器传递到我的前端 reactjs 以显示在我的 Web 应用程序中?



这是我的服务器端索引.js。

const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");
app.use(cors());
app.use(express.json()); 
//getting all species
app.get('/species', async (req, res) => {
try {
const allspecies = await pool.query("SELECT * FROM speciesdata");
res.json(allspecies.rows);
console.log(allspecies.rows)
} catch (err) {
console.log(err.message)
}
})
//getting one species
app.get("/species/:id", async (req, res) => {
try {
const {id} = req.params;
const families = await pool.query("SELECT * FROM speciesdata WHERE id = $1", [id]);
res.json(families.rows);  
console.log(families)

} catch (err) {
console.log(err.message)
}
})

app.listen(5000, () => {
console.log("server has started on port 5000")
})

在服务器端,我获取一个物种的查询在我的本地主机:5000 上工作,我可以查看我的查询结果。当控制台日志 req.params 时,我{id: 1}我的 url 是否 http://localhost:5000/species/1 并且显示的 json 文件是:

[{"id":1,"name":"American Robin","description":"Widespread, common, and conspicuous, these medium-size birds can be found in every state in the Lower 48, every Canadian province, and Alaska. They are easy to spot with their rusty orange bellies and gray backs. Often seen running upright across lawns and meadows while foraging for worms, robins can be found from cities and towns to parks and forests, where their rich, throaty songs provide a constant soundtrack to our daily lives.","img":"https://nas-national-prod.s3.amazonaws.com/aud_gbbc-2016_american-robin_32533_kk_ca_photo-donald_metzner.jpg"}]

这是我的前端反应应用程序。

function SingleSpeciesPage({match, families}) {
console.log(families)
useEffect(()=> {
const getFamily = async() => {
try {
const response = await fetch(`http://localhost:5000/species/${families.id}`)
const jsonData = await response.json();

} catch (err) {
console.log(err)
}
}
getFamily();
})

在我的前端,我正在尝试获取单个物种并通过将族作为 props 传递在我的网站应用程序上呈现该物种,以便本地服务器可以使用我在这里将其命名为families的给定id获取数据。在families的控制台日志上,它返回我undefined。我的捕获错误消息也被打印出来,TypeError: Cannot read property 'id' of undefined.

这是我在反应中使用的路由器。

import React from 'react';
import './App.css';
import HomePage from './pages/HomePage';
import { BrowserRouter as Switch, Router, Route } from "react-router-dom";
import  createBrowserHistory from 'history/createBrowserHistory';
import SingleSpeciesPage from './pages/SingleSpeciesPage';
import SingleBird from './pages/SingleBird';
const customHistory = createBrowserHistory();
function App() {
return (
<Router history={customHistory}>
<Switch>
<Route exact path='/'>
<HomePage/>
</Route>
{/* Only when u use this format component={} then the params can be pass down */}
<Route exact path ='/species/:familyId' component={SingleSpeciesPage}/>

</Switch>
</Router>
);
}
export default App;

我的结论是我的 localhost3000 没有从我的 localhost5000 获取数据。这是我第一次在我的前端处理后端,所以如果我的问题措辞不佳,请理解。提前感谢!

你在 React 组件中传递了错误的道具名称。

你正在使用的families在前端的任何道具中都不匹配。

所以看看props,你就会意识到发生了什么

function SingleSpeciesPage(props) {
console.log(props) 
useEffect(()=> {
const getFamily = async() => {
try {
const response = await fetch(`http://localhost:5000/species/${props.match.params.familyId}`)
const jsonData = await response.json();

} catch (err) {
console.log(err)
}
}
getFamily();
})

您的页面应该能够通过localhost:3000/species/1访问

最新更新