[英]How can I pass a unique identifier from my express backend server to my frontend reactjs to be displayed in my web application?
This is my server side index.js.这是我的服务器端 index.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")
})
In the server side, my query for getting one species is working as on my localhost:5000, i can view my query results.在服务器端,我获取一个物种的查询在我的 localhost:5000 上运行,我可以查看我的查询结果。 When console log req.params i got {id: 1}
if my url is http://localhost:5000/species/1 and json file displayed is:当控制台日志 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"}]
This is my frontend reactjs application.这是我的前端 reactjs 应用程序。
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();
})
On my front end side, I am trying to fetch a single species and render that species on my website application by passing the families as props so that the local server can fetch the data using the id
given which i named it here as families
.在我的前端,我正在尝试获取单个物种并通过将家庭作为道具传递来在我的网站应用程序上呈现该物种,以便本地服务器可以使用给定的id
获取数据,我在这里将其命名为families
。 Upon console log of families
, it return me undefined
.根据families
的控制台日志,它返回我undefined
。 And my catch error message is also printed out, TypeError: Cannot read property 'id' of undefined
.并且我的 catch 错误消息也被打印出来, TypeError: Cannot read property 'id' of undefined
。
This is the router i used in react.这是我在反应中使用的路由器。
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;
My conclusion was that my localhost3000 is not fetching data from my localhost5000.我的结论是我的 localhost3000 没有从我的 localhost5000 获取数据。 This is my first time dealing with a backend on my frontend so if my question is poorly phrased, please understand.这是我第一次在前端处理后端,所以如果我的问题措辞不当,请理解。 Thanks in advance!提前致谢!
You're passing wrong props name in React Component.您在 React 组件中传递了错误的道具名称。
The families
you're using is not match in any props in Frontend.您使用的families
在前端的任何道具中都不匹配。
So take a look at props
and you'll realise what happen所以看看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();
})
And your page should able to access via localhost:3000/species/1
您的页面应该能够通过localhost:3000/species/1
访问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.