henrikbossart
henrikbossart

Reputation: 41

NodeJS not serving static html

I am having a problem serving my html file on my node server.

The code in "index.js" looks like this:

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

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

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

app.listen(8081, function () {
  console.log('Magic is happening on port 8081!');
});

Here is a picture of my file structure:

File structure

When i run the server, it gives me this error:

TypeError: path must be absolute or specify root to res.sendFile

In the end i need a server that can serve several different pages, this is only the first page i am serving (no sense in going further if the first page doesn't work..)

What am i doing wrong?

Upvotes: 2

Views: 804

Answers (6)

henrikbossart
henrikbossart

Reputation: 41

Ok, so i figured out a solution.

I changed the whole setup to this

var express     = require('express');
var app         = express();
var port        = process.env.PORT || 8081;

var path        = require('path');
var http        = require('http');
var router      = express.Router();
//var data        = require('./routes/data');

// Setting the view engine and defining paths
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));

require('./routes/routes')(app);

app.listen(port, function () {
    console.log('server running on port ' + port);
});

module.exports = app;

This is now working the way i wanted it to. Not sure if its optimal or perfect, but i think it does the job.

Thank you all for your help!!

Upvotes: 1

num8er
num8er

Reputation: 19372

Here is my recommendations:

1) Move views folder to same location with index.js

2) Update code of index.js:

const 
    DEBUG_MODE = (process.env.DEBUG == 1),
    express = require('express'),
    app = express();

/* DEFINE VIEW RENDERER */
app.set('view cache', !DEBUG_MODE);
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

/* DEFINE VIEW FILES LOCATION */
app.set('views', __dirname + '/views');

/* KEEP STATIC FILES IN SOME CONSTANT (GROUPED) PLACE, EX.: /assets */
app.use('/assets/css', express.static(__dirname + '/public/css'));
app.use('/assets/images', express.static(__dirname + '/public/images'));

/* RENDER home VIEW FOR ROOT REEQUEST */    
app.all('/', (req, res) => res.render('home'));

app.listen(8081, function () {
  console.log('Magic is happening on port 8081!');
});

serving view files is job of express app that is done by simply calling res.render('view-name'); (without extension, cuz already defined in app.engine('html', ...);

P.S. If You need example: https://bitbucket.org/num8er/sum-az-website/src

Upvotes: 0

Artem Ilchenko
Artem Ilchenko

Reputation: 1035

For your dir structure your code must looks like

app.use(express.static(path.join(__dirname, 'public', 'views'), {index: 'home.html'})); app.use(express.static(path.join(__dirname, 'public'))); Serving static files examples

Upvotes: 0

raj peer
raj peer

Reputation: 718

Run this code, keep on html file in same folder, ex: index.html in browser, localhost:9000/index.html

    var http = require("http");
    var fs = require("fs");
    var port = 9000;

    //create server
    http.createServer(function(req,resp){
        reqUrl = req.url;
        var day = reqUrl.slice(1,reqUrl.length-1);
        file = reqUrl;
        callPage(req,resp,file);
    }).listen(port); 


    function callPage(req,resp,fileName){

        fileName = reqUrl.slice(1,reqUrl.length);
        console.log(fileName)
        fs.readFile(fileName,function(err,html){
            if(err){
                throw err;
            }

            resp.writeHead(200,{"content-type":"text/html"});
            resp.write(html);
            resp.end();
        });

    }

Upvotes: 0

t.niese
t.niese

Reputation: 40842

The documentation and the error tell you that sendFile that [...]Unless the root option is set in the options object, path must be an absolute path to the file[...] (res.sendFile(path [, options] [, fn]))

So you have to write:

res.sendFile(path.join(__dirname, 'public/views/home.html'))

Upvotes: 0

num8er
num8er

Reputation: 19372

To make this code work:

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

app.use(express.static(path.join(__dirname, 'public')));

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

app.listen(8081, function () {
  console.log('Magic is happening on port 8081!');
});

You must have such dir structure:

views
  |-home.html
public
  |- some files here
index.js

Upvotes: 0

Related Questions