【问题标题】:Getting Data from custom URL from express server using React使用 React 从快速服务器的自定义 URL 获取数据
【发布时间】:2021-09-01 15:07:45
【问题描述】:

我正在学习 react 和 express,我正在尝试制作一个简单的博客网站,其中 React 作为我的前端,Express 服务器作为后端。

对于 Express 服务器,这是我的代码:-(app.js)

const express=require('express');
var _ = require('lodash');
const app=express();

app.use(express.static(__dirname));

app.get("/",function(req,res){
    res.sendFile(__dirname+"/client/public/index.html");
});

app.get("/api",function(req,res){
    res.send({heading: "'Hello World"});
});

app.get("/posts/:postName",function(req,res){  //---->want to get data linked with the 'postName'
    let post=req.params.postName;
    console.log(post);
    res.json({postName:post});
});



app.listen(8080,function(){
    console.log("Server is running...");
});

这是我通过使用 React 的在线资源创建的东西:-(App.jsx)

import React from "react";

function App() {
    const [data, setData] = React.useState(null);
  

我应该如何在下面的代码中传递在 url 中输入的帖子名称?例如,我输入 'localhost:3000/posts/day1' 以便我可以找到有关名为 day1 的帖子的信息并呈现该博客帖子

    React.useEffect(() => {
      fetch("/posts/")
        .then((res) => res.json())
        .then((data) => setData(data.users));
    }, []);
  
    return (
      <div className="App">
        <header className="App-header">
          <p>{!data ? "Loading..." : data}</p>
        </header>
      </div>
    );
  }
  

export default App;

我希望我没有以错误的方式接近它。

【问题讨论】:

标签: node.js reactjs express


【解决方案1】:

你想要实现的是利用 React Router。 这位官方code example足以让你继续使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 2016-10-13
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    相关资源
    最近更新 更多