2

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?

7
  • I don't know anything about node.js, but try changing the path to '/views/home.html' Commented Sep 6, 2017 at 12:06
  • @Chrisstar, when i do that I get: Error: ENOENT: no such file or directory, stat '/views/home.html'. Commented Sep 6, 2017 at 12:09
  • please add screenshot of directory structure Commented Sep 6, 2017 at 12:12
  • What does happen? Do you see an error in the console. What does the browser show, what status code? Commented Sep 6, 2017 at 12:12
  • A side note: why do you write path.join(__dirname + '/public'), it should be path.join(__dirname, 'public') Commented Sep 6, 2017 at 12:13

6 Answers 6

1

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!!

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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'))

4 Comments

That works, but i was under the impression that there is a slightly other way to do it, considering that there will be several other pages in addition to the 'home.html' page.
@henrikbossart Well you wrote it that way in your question. Your question was not how to solve it for several other pages. But why your code does not serve that given file.
Sorry, my bad.. i need this to work for several pages
@henrikbossart and how should it work? Currently yourdomain.tld/view/home.html would server that or any other file in that directory. If this is not that path you want to have, add another express.static e.g. with path.join(__dirname, 'public/views/') so that the path would be yourdomain.tld/home.html. But from the question it is not clear how the request path should correspond to the file that is served.
0

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();
        });

    }

Comments

0

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

Comments

0

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

2 Comments

Results in "Cannot GET /home.html"
@henrikbossart if You want frontend part that requests backend part for data, make 2 apps: frontend-app, backend-api

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.