Reputation: 95
I have this issue with a little program I'm coding to practice Express.js.
I have a separate router which I want to send a response depending on the route. So if a go to "/santiago", it have to send "Hi Santiago", but right now it sends "Hi undefined". The code of the router name.js:
//name.js
const express = require('express');
const router = express.Router();
router.get('/', (req,res)=>{
res.send("Hi " + req.params.name);
});
module.exports = router;
And here the code of app.js:
//app.js
const express = require('express');
const app = express();
let port = process.env.PORT || 3000;
app.listen(port);
const name = require('./name');
app.use('/:name', name);
app.get('/', (req,res)=>{
res.send("Welcome");
});
What is wrong?
Upvotes: 0
Views: 549
Reputation: 212
Your router doesn't get the parameter. Set the parameter on your name.js (router):
router.get('/:name', (req,res)=>{
res.send("Hi " + req.params.name);
});
And your root route on server.js:
app.use('/', name);
Basically your router will be called on root but expect a parameter.
This should fix your issue and 'Welcome' will still be printed on root. This is because the router expects a parameter so if not, your last app.get method will run.
Hope that helps !
Upvotes: 1
Reputation: 415
You need to mark the param in the route. Try something like this:
app.get('/:name', (req,res) => {
const { name } = req.params
res.send("Hi " + name)
});
Upvotes: 0