Express res.sendFile() with Query String Express res.sendFile() with Query String express express

Express res.sendFile() with Query String


You cannot pass query string parameters with res.sendFile(). You have to specify the file path as the 1st parameter in res.sendFile()

Syntax is :

res.sendFile(path [, options] [, fn])

So what you can do is,

  1. Use the query string with a route, say route1 (refer the below code)

  2. Inside the GET method of route1, use res.sendFile()

    app.get('/route1',function(req,res){  res.sendFile(path.join(__dirname, '../public', '/index.html'));});res.redirect('/route1?id=123');

See also Express API documentation of res.sendFile and res.redirect.


This answer is to further add on to @Marie Sajan's answer by covering the question asked by @Sky in a comment.

To access id in index.html after using @Marie Sajan's answer you can use normal client-side javascript. You could do something like this in <script> tags in your html file:

var query = location.href.split("?")[1];

This would get you a string such as "id=123&name=ted".From here you can use javascript to get the value of id. The full code might look something like this:

var query = location.href.split("?")[1]; //A string of all parameters in the URLvar params = query.split("&"); //Turns the string into an array of parametersvar id; //To store the value of idparams.forEach((param, index) => {    //This checks each key-value pair, in the format key=value, for the specific id key we want    var key = param.split("=")[0]; //In id=123, this would be "id"    var value = param.split("=")[1]; //In id=123, this would be "123" (as a String)    if (key == "id") id = value;});

Now the javascript variable id will contain the value "123".

If you were also looking for the values of more query parameters in addition to the id key, you would simply add more if statements inside the forEach to check for those specific keys.

In a link such as "http://google.com/?q=stack+overflow&id=123", this code would be able to get the value "123" of id when implemented as client-side javascript either directly in the HTML file in <script> tags, or in a separate client-side js file that is used by the HTML file. Note that @Marie Sajan's answer is entirely server-side code, while this code is what would be used on the client-side.

This answer does not address the original question, it only adds further useful content to an accepted answer to the question based on the needs of viewers of this page.