Reputation: 47
I have an express api endpoints for different purpose, but a single one is returning results for all the endpoints.
example.
api/:id
returns id.
api/:id?region=east
returns {region: "east"}
I know in the first case we use req.params
, second case req.query
.
My problem is for both calls, the results are from first case only.
How can I resolve this?
sample code app.js file
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.use('/api', require(./server/user.js));
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port} `));
#user.js file
const express = require('express');
const router = express.Router();
//endpoint api/10
//ie 10 is the id
router.get('/:id', (req,res) =>{
let id = req.params;
return res.json(id);
});
//note the second router should be using query string
//ie api/10?region=east
router.get('/:id', (req,res) =>{
let id = req.params;
return res.json(id);
});
My problem is the second api endpoint doesn't work. it executes the first api endpoint.
1 Updates above
Upvotes: 1
Views: 2946
Reputation: 623
You can use single route instead of making two different routes, you will just need to check for query string in the request as shown below.
router.get('/:id', (req,res) =>{
let id = req.params;
let region;
if(req.query){
region = req.query.region;
}
return res.json(id);
});
Upvotes: 1