slevin
slevin

Reputation: 3888

cannot set node and express to serve files

I use Windows 7. I installed nodes 0.10.12 and latest version of express and express-generator both globally. I

created a new express project named nodetest1 and installed all dependencies succesfully using npm install.

Going to http://localhost:3000/ renders Express Welcome to Express -so it works.

I try to use node and express as simple server now, just use some html files.

According to the book "Jump Start Node.js" by Don Nguyen Copyright © 2012 SitePoint Pty. Ltd. [pages 9-11] , I edited my

app.js file and added

var fs = require('fs');

and after

var routes = require('./routes/index');
var users = require('./routes/users');

I added

app.get('/form', function(req, res) {
  fs.readFile('./form.html', function(error, content) {
    if (error) {
      res.writeHead(500);
      res.end();
    } else {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(content, 'utf-8');
    }
  });
});

Then I created a simple form.html file put it in the nodetest1 directory, restarted my server and in the command line I get

app.get('/form', function(req, res) {
TypeError : Cannot call method 'get' of undefined
npm ERR! weird error 8
npm ERR! not ok code 0

What am I doing wrong? I just want to use simple html, not Jade.

Also do I have to edit the app.js for every html file I add? And where will I add the new files, in what folder?

Thanks in advance

Upvotes: 0

Views: 73

Answers (1)

Jordonias
Jordonias

Reputation: 5848

Did you create the express app?

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

Also, you can just use res.sendFile for this.

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

If you are serving up a lot of static files you may want to look into express.static middleware. http://expressjs.com/4x/api.html#app.use

This will serve up all files you put in your public directory:

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

Directory structure:

|-app.js
|-public
| |-index.html
| |-form.html

You're form.html will be served to localhost:3000/form.html

If you wan't to serve up html files without an extension you can use the solution found in this other answer to a different question by @robertklep. Any way to serve static html files from express without the extension?

app.use(function(req, res, next) {
  if (req.path.indexOf('.') === -1) {
    var file = publicdir + req.path + '.html';
    fs.exists(file, function(exists) {
      if (exists)
        req.url += '.html';
      next();
    });
  } else {
    next();
  }
});

You'll want this to be before app.use(express.static(__dirname + 'public'));


Note: The book you mentioned was published Dec 2, 2012. Express 3 was released Oct 23, 2013 according to github. The current version is 4.8.5. You may want to use a more current reference.

Upvotes: 1

Related Questions