Krishnandu Sarkar Krishnandu Sarkar - 1 year ago 102
HTML Question

Express res.sendFile() with Query String

I have successfully implemented serving static files using res.sendFile() but it doesn't works if I add some querystring.

E.g. the below code works absolutely fine.

res.sendFile(path.join(__dirname, '../public', '/index.html'));


But if I do this, it fails

res.sendFile(path.join(__dirname, '../public', '/index.html?id=' + req.params.id));

res.sendFile(path.join(__dirname, '../public', '/index.html?id=123'));


Then I get the below error

ENOENT, stat '/Users/krishnandu/Documents/Project/public/index.html?id=123'

404

Error: ENOENT, stat '/Users/krishnandu/Documents/Project/public/index.html?id=123'
at Error (native)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download