1

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

6
  • Can you post more code to show a couple the entry point and a few routes? Commented Jul 3, 2019 at 19:56
  • @Kose You want to use params and query string within same endpoint.? Commented Jul 3, 2019 at 19:58
  • The question is unclear. Please be more explicit and precise. Commented Jul 3, 2019 at 20:07
  • @ShubhamSharma yes Commented Jul 3, 2019 at 20:36
  • @Kose you can use both req.params and req.query to access then within the same endpoint. Commented Jul 3, 2019 at 20:38

1 Answer 1

1

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); 
});
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.