Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get index.html to show with Express in Nodejs

I'm trying to run my first express app, but can't seem to get my webpage to show. I have the following code:

var fs = require("fs");
var config = JSON.parse(fs.readFileSync("files/config.json"));  
var host = config.host;
var port = config.port;
var express = require("express");

var app = express();

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

app.get("/", function(request, response){
    response.send("hello!");
});

app.listen(port, host);
console.log("Listening on port" + port);

Here is my directory tree

nodejs/
    js/
        javascript.js
    public/
        index.html

I know the server is running because I get my "Hello!" response in the browser when I run 127.0.0.01:1337

But when I try and type the webpage 1227.0.0.1:1337/index.html, I get Cannot GET /index.html displayed in the browser

So I'm guessing it's something wrong with the name value in my get method, but can't figure out what it is and how to fix it.

like image 730
Paul Samsotha Avatar asked Oct 27 '13 16:10

Paul Samsotha


1 Answers

Your app will only route page requests that are set up at the time of your app.use(app.router) call. So reorder your app.use calls to be one of the following:

Express 3

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

__dirname is the directory that the executing script resides in, so because that lives in the js directory that's a peer to public your code would need to be:

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

Express 4

Express 4 removes the need to manually do app.use(app.router). With Express 4 you just need:

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

like image 81
JohnnyHK Avatar answered Sep 28 '22 00:09

JohnnyHK