So I have an api where I have to pass car make, model, year in URL. I have express router post call to get the query params and set to object.
I need to be able to accept params in URL, so say localhost:8080/cars/[not sure of this syntax but I need make:Audi?model:A4?year:2017]
I'm not sure of & and ? in above url, so please correct it.
router.post('/:make[not sure of this either but need to accept all params]),
function(req,res)
{
var make: req.query.make // here I should be able to get make of car and it should match query url
}
Please explain the actual URL I need to make post call and the URL for router.post
~SRJ
CodePudding user response:
You have two ways you can use URL params in Express.js.
- Using route parameters.
req.params
- with this method, you will need to specify the name of the param you are expecting to receive in the URL in your server route:
app.get('/cars/:make/:model/:year', function (req, res) {
res.send(req.params)
})
and the URL will hold the values of each param in the order they appear in the route:
localhost:8080/cars/Audi/A4/2017
this will return:
{
"make": "Audi",
"model": "A4",
"year": "2017"
}
you can access the specific URL param by simply adding the name of the param specified in your route like so: res.send(req.params.make)
- Using query parameter.
req.query
- this will look closer to what you did. With this method, you don't need to specify the param name in your route, so your route will be:
app.get('/cars', function (req, res) {
res.send(req.query)
})
the URL will be like a key:value pair, starting with ?
to specify that this part of the URL is the beginning of the query params, following with &
for each additional query param:
localhost:8080/cars?make=Audi&model=A4&year=2017
this will also return:
{
"make": "Audi",
"model": "A4",
"year": "2017"
}
same as the route parameters method, you can also access a specific query param by adding it to the query param like so: req.query.model
CodePudding user response:
You can call your URL like this and below should work: localhost:8080/cars/Audi&A4&2017
router.post('/:make&:model&:year),
function(req,res)
{
const car = {
make: req.params.make,
model: req.params.model,
year: req.params.year
}
}
That will give you all properties in desired variables.