BaSic BaSic - 4 months ago 34
Node.js Question

URL Query Parameters

i'm facing a problem.

I'm using node and express.

Index.html
contains 2 inputs.

<form action="/profile" method="get">
<input id="variable1" name="variable1" type="text" placeholder="..."> //xxx
Select :
<select id="variable2" name="variable2">
<optgroup label="y">
<option value="variable">yyy</option>
</select>


in
profile.js
I got:

router.get('/profile', function(req, res){

var var1 = req.params.variable1;
var var2 = req.params.variable2;

res.render('result');
}


Node renders
result.html
, but the URL i get is

https://localhost:3030/profile?variable1=xxx&variable2=yyy



The question is how to get
https://localhost:3030/profile/xxx/yyy

instead of the URL above?

Answer

Define your route as: /profile/:var1/:var2

Now access them using req.params:

var var1 = req.params.var1;
var var2 = req.params.var2;

UPDATED ANSWER:

Though, it may be a bit dirty, you can try this as an alternative if you can't change the url where the form is submitted( though you can easily do that using javascript on form submission ):

router.get('/profile', function(req, res){

var var1 = req.query.variable1;
var var2 = req.query.variable2;
res.redirect('/profile/'+var1+'/'+var2);
}

router.get('/profile/:var1/:var2', function( req, res ){
var var1 = req.params.variable1;
var var2 = req.params.variable2;
res.render('result');
});