0

I am learning react and express and I was trying to make a simple blog website with React as my Front end and Express server for the backend.

For the Express Server this is my code:-(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...");
});

And this is something I was able to create by using online sources for React:-(App.jsx)

import React from "react";

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

How should I pass the postname typed in url in the below code?For example I type 'localhost:3000/posts/day1' so that I can find info about post named day1 and render that blog post

    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;

I hope I am not approaching it in a wrong way.

1

1 Answer 1

0

What you want to achieve is to make use of React Router. This official code example is enough to get you going with it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.