Raj
Raj

Reputation: 107

Node.js path error

Under my server.js i have the following

app.use(express.static(__dirname + '/public'));

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

app.get('/report', function(req, res){
    res.sendFile('report.html');
});

When i start the server and render on http://localhost:8000 i am able to see index.html, but on http://localhost:8000/report i am unable to render report.html and instead i get an path error path must be absolute or specify root to res.sendFile

My directory structure is

public
   index.html
   report.html

Why i am getting this error?

Upvotes: 1

Views: 3724

Answers (2)

jfriend00
jfriend00

Reputation: 707148

By default, express.static() will serve up index.html when just / is requested (see reference in the doc). So, your index.html is being served by the express.static() middleware, not by your app.get('/', ...) route.

So, both your app.get() routes would likely have the exact same issue. The first one just isn't being called because your express.static() configuration is already handling that request and sending back index.html.

The /report route is not being handled by express.static() because report is not the same request as report.html. Thus, the middleware does not handle the request so then your misconfigured app.get('/report', ...) handler is invoked and you get the error about it being misconfigured.

This should be all you need:

var express = require("express");
var app = express();

app.use(express.static(__dirname + '/public'));

app.get('/report', function(req, res){
    res.sendFile(__dirname + "/public/report.html");
});

app.listen(8080);

Or, you can use the path module and join the pieces with path.join():

var path = require("path");

And, then serve the file with this:

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

In my own sample nodejs app, either of these res.sendFile() options work.

Upvotes: 2

Z T
Z T

Reputation: 570

npm install path

then, you have to specify the root path:

var express = require('express');
var app = express();
var path = require('path');

app.use(express.static(__dirname + '/public'));

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

app.get('/report', function(req, res){
    res.sendFile('report.html', { root: path.join(__dirname, './public') });
});

app.listen(8000);

Upvotes: 1

Related Questions