1

I tried to send a static html file for two routes '/' and '/test'. It is working for '/' route but not '/test'/

I am getting following error:

TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (E:\sairam\javascript\node\Node middleware\node_modules\express\lib\response.js:421:11)
    at E:\sairam\javascript\node\Node middleware\index.js:11:9
    at Layer.handle [as handle_request] (E:\sairam\javascript\node\Node middleware\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\sairam\javascript\node\Node middleware\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (E:\sairam\javascript\node\Node middleware\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (E:\sairam\javascript\node\Node middleware\node_modules\express\lib\router\layer.js:95:5)
    at E:\sairam\javascript\node\Node middleware\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (E:\sairam\javascript\node\Node middleware\node_modules\express\lib\router\index.js:335:12)
    at next (E:\sairam\javascript\node\Node middleware\node_modules\express\lib\router\index.js:275:10)
    at SendStream.error (E:\sairam\javascript\node\Node middleware\node_modules\serve-static\index.js:121:7)

This is my app.js

let express = require('express');
let app = express();

app.use(express.static('public'));

app.get('/', function(req,res){
    res.sendFile('index.html');
    res.end();
})
app.get('/test', function(req,res){
    res.sendFile('index.html');
    res.end();
})
app.listen(3000);

index.html file is in public folder.. that was am serving as static container.

Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
Sairam
  • 29
  • 1
  • Possible duplicate of [node.js TypeError: path must be absolute or specify root to res.sendFile \[failed to parse JSON\]](https://stackoverflow.com/questions/26079611/node-js-typeerror-path-must-be-absolute-or-specify-root-to-res-sendfile-failed) – Saurabh Mistry Mar 11 '19 at 05:52

2 Answers2

2

If you want to use relative paths for res.sendFile, you need to specify the root option. Use the following code to serve index.html, assuming it resides in the same directory as the Node app source.

You can get the current directory with __dirname.

app.get('/', function(req,res){
    res.sendFile('index.html',{root:__dirname});
})
app.get('/test', function(req,res){
    res.sendFile('index.html',{root:__dirname});
})

Please also reference node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

(Thank you to Saurabh Mistry for the reference)

HumbleOne
  • 170
  • 10
TheRealOrange
  • 115
  • 1
  • 1
  • 9
0

try this way :

app.get(['/','test'], function(req,res){
    res.sendFile(__dirname + '/public/'+ 'index.html');
});
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71