简体   繁体   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?

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.

相关问题 我可以在前端使用后端的OAuth令牌吗? - Can I use an OAuth token from backend in my frontend? 如何从我的 express 应用程序获取数据到我的前端组件(在 React 中)? - How can I get data from my express app to my component in the frontend(which is in React)? 如何将数据发送到Express中的前端js文件 - How can I send data to my frontend js files in express 无法通过我的前端从我的节点 js 服务器下载图像文件(我的后端和前端是解耦的) - Failed to download an image file from my node js server through my frontend (my backend and frontend are decoupled) 如何在node.js-Backend和前端中的单独js文件中使用函数? - How can I use a function in a separate js file in my node.js-Backend as well as in my frontend? 如何将后端查询的结果返回到前端以显示在页面上 - How can I return the results of my backend Query onto my frontend to display on a page NodeJs:如何从我的 HTML 前端访问我的 JavaScript 后端的功能? - NodeJs: How do I access the functions of my JavaScript backend from my HTML frontend? 作为前端开发人员,我如何使 My Server BASEURL 动态化? - How i can make My Server BASEURL dynamic as a frontend developer? 通过我的前端从节点快速服务器下载 JSON 文件 - Download JSON file from a node express server through my frontend 如何在我的后端 using.fetch() 中将参数传递给 function? ReactJS + 节点 - How to pass an argument to a function in my backend using .fetch()? ReactJS + Node
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM