簡體   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