Home > Software design >  How can I use Express to handle a request for specific route in a React Router app?
How can I use Express to handle a request for specific route in a React Router app?

Time:02-04

I'm making an app using React Router with an Express server. As is, the server only responds to requests to the root endpoint, and React Router handles navigation from there. But I'd like to be able to handle requests to say myapp.com/user/a_cool_user_id, instead of just to myapp.com. How can I instruct my Express server to simultaneously serve the app and navigate to that particular route?

I'm at a loss for how to proceed. I'm thinking that my server needs to just serve the same app, but then in the response I'm not sure how to also tell React Router to navigate appropriately.

Edit: In case it clarifies things: I'm hoping for this to work when the client is not yet at my webpage. (More specifically, I'd ultimately like to generate a QR code that takes the client to the myapp.com/user/a_cool_user_id route.)

CodePudding user response:

This is a hello world example using express:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

The code above expose an endpoint on the root, exactly as your case (myapp.com)

const express = require('express')
const app = express()
app.use(express.json())
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.get('/user/:id', (req, res) => {
  const userId = req.params.id
  const user = // Implement your code for retriving a user here
  res.send(user)
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

This second piece of code exposes one endpoint at the root (myapp.com) and another one on /user/a_cool_user_id (myapp.com/user/a_cool_user_id)

CodePudding user response:

I figured out a way of doing this. I can give the client a URI including a query parameter, say myapp.com?user=a_cool_user_id. Then, inside of my React Router app, I check for the user query parameter, and if it exists, execute the function navigate('/user/a_cool_user_id') (using the useNavigate hook).

  • Related