3
votes

I am trying to create a contacts app with angularjs. I have created a file in the root directory of the project called server.js. Here is the code:

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

app
    .use(express.static('./public'))
    .get('*', function (req, res) {
        res.sendfile('public/main.html');
    })
    .listen(3000);

When I go to localhost:3000, this is the error message that comes up.

TypeError: path must be absolute or specify root to res.sendFile at ServerResponse.sendFile (D:\Workspace\contacts\node_modules\express\lib\response.js:389:11) at D:\Workspace\contacts\server.js:7:7 at Layer.handle [as handle_request] (D:\Workspace\contacts\node_modules\express\lib\router\layer.js:82:5) at next (D:\Workspace\contacts\node_modules\express\lib\router\route.js:100:13) at Route.dispatch (D:\Workspace\contacts\node_modules\express\lib\router\route.js:81:3) at Layer.handle [as handle_request] (D:\Workspace\contacts\node_modules\express\lib\router\layer.js:82:5) at D:\Workspace\contacts\node_modules\express\lib\router\index.js:235:24 at Function.proto.process_params (D:\Workspace\contacts\node_modules\express\lib\router\index.js:313:12) at D:\Workspace\contacts\node_modules\express\lib\router\index.js:229:12 at Function.match_layer (D:\Workspace\contacts\node_modules\express\lib\router\index.js:296:3)

Does anyone have any suggestions? Any help would be greatly appreciated.

4

4 Answers

2
votes
var path = require('path');  

res.sendFile(path.join(__dirname, './public', 'main.html'));
1
votes

Try this:

res.sendfile(__dirname + '/public/main.html');

You have to specify an absolute path (starting with /)

0
votes

You should change the path in your get('*') function to an absolute path:

res.sendfile('public/main.html');

You can use express' __dirname for that.

0
votes

Make sure that you access the public directory relative to the current working directory. Below changes should work in your case

var express = require('express'),
    app = express(),
    path = require('path'),
    publicDir = path.join(__dirname, 'public');

app.use(express.static(publicDir))
app.get('*', function(req, res){
    res.sendFile(path.join(publicDir, 'main.html'));
}).listen(3000);