繁体   English   中英

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

[英]How can I pass a unique identifier from my express backend server to my frontend reactjs to be displayed in my web application?

这是我的服务器端 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")
})

在服务器端,我获取一个物种的查询在我的 localhost: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"}]

这是我的前端 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();
  })

在我的前端,我正在尝试获取单个物种并通过将家庭作为道具传递来在我的网站应用程序上呈现该物种,以便本地服务器可以使用给定的id获取数据,我在这里将其命名为families 根据families的控制台日志,它返回我undefined 并且我的 catch 错误消息也被打印出来, 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访问

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM