Angularjs - TypeError: path must be absolute or give root to res.sendFile

I am trying to build a contacts app with angularjs. I created a file in my project root named 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 error message appears.

TypeError: path must be absolute or point to root for res.sendFile on server ServerResponse.sendFile (D: \ Workspace \ contacts \ node_modules \ express \ lib \ response.js: 389: 11) in D: \ Workspace \ contacts \ server. js: 7: 7 on Layer.handle [as handle_request] (D: \ Workspace \ contacts \ node_modules \ express \ lib \ router \ layer.js: 82: 5) on next (D: \ Workspace \ contacts \ node_modules \ express \ lib \ router \ route.js: 100: 13) to Route.dispatch (D: \ Workspace \ contacts \ node_modules \ express \ lib \ router \ route.js: 81: 3) to Layer.handle [as handle_request] ( D: \ Workspace \ contacts \ node_modules \ express \ lib \ router \ layer.js: 82: 5) in D: \ Workspace \ contacts \ node_modules \ express \ lib \ router \ index.js: 235: 24 in Function.proto .process_params (D: \ Workspace \ contacts \ node_modules \ express \ lib \ router \ index.js: 313: 12) to D:\ Workspace \ contacts \ node_modules \ express \ lib \ router \ index.js: 229: 12 in 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.

+3


source to share


4 answers


var path = require('path');  

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

      



+2


source


Try the following:

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

      



You must provide an absolute path (starting with /)

+1


source


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

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

      

You can use the expression ' __dirname

for this.

0


source


Make sure you are referring to 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);

      

0


source







All Articles