How to write an API route with query string parameters in Express.js

1.1k Views Asked by At

Trying to write a simple route, getting a record by it's id property/column

const router = require("express").Router();    
router.get("/record/:id", getRecordById)    // CHANGE HERE

This is how I'm able to use for frontend ajax -

http://localhost:3001/record/1

What do I need to change, to be able to use the route as

http://localhost:3001/?record=1
2

There are 2 best solutions below

0
On BEST ANSWER

You should create a route like this.

router.get("/", function (req, res) {
  // Get record id
  const record_id = req.query.record;
});
0
On

In your case

API: router.get("/record", getRecordById)

URL: http://localhost:3001/record?id=1

Get the query string in api: req.query.id