Reputation: 1282
I get an error trying to render a simple html page using NodeJS and Express 4.10.4, with the following code:
var path = require('path');
var express = require('express');
var logger = require('morgan');
var app = express();
app.set('port', process.env.PORT || 8080);
app.use(express.static(path.join(__dirname, '/client')));
app.set('view engine', 'html');
app.use(logger('dev'));
app.get('*', function (req, res) {
res.sendFile('/index.html');
});
app.use(function (err, req, res, next) {
console.log(err.stack);
res.status(500).send({message: err.message});
});
console.log('Server has started on port: '+ app.get('port'));
My index.html page is within the client folder, it is rendered in my browser but I get the following error:
Error: ENOENT, stat 'c:\index.html'
Has anyone an idea what's the issue?
Upvotes: 1
Views: 2395
Reputation: 595
The error code 'ENOENT' is a unix error code indicating absence of file.
Check here: http://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Errors/unix_system_errors.html
I'll advise you use sendFile method of express response with the options and callback stated in the API here: http://expressjs.com/api.html#res.sendFile. Use the options object literal to indicate the location of the html file. See sample below. At first request there is no error. At subsequent requests, the callback will receive an error with response status code 304 - read about what this means.
See below for an amendment to your code and see if it helps you.
var path = require('path');
var express = require('express');
var logger = require('morgan');
var app = express();
app.set('port', process.env.PORT || 9090);
app.use(express.static(path.join(__dirname, '/client')));
app.set('view engine', 'html');
app.use(logger('dev'));
app.get('*', function (req, res) {
var options = {
root: __dirname + '/client/'
};
res.sendFile('/index.html', options, function (err) {
if (err) {
console.log('Error in res : %s, status code: %s', err, res.statusCode);
res.status(err.status).end();
}
else {
console.log('Sent: ', 'index.html');
}
});
});
app.use(function (err, req, res, next) {
console.log('error stack is here : ' + err.stack);
res.status(500).send({message: err.message});
});
app.listen(app.get('port'), function() {
console.log('Server has started on port: '+ app.get('port'));
});
Upvotes: 3