mupersan82
mupersan82

Reputation: 567

Serving HTML files with Express

UPDATE: It works if I access edit.html by specifying address/edit.html but not address/edit.

I have a problem serving html files other than index.html.

My server.js looks like this:

// EXPRESS CONFIG
app.use(express.favicon());
app.use(express.bodyParser());
app.use(express.static(__dirname + "/public/views"));
app.use(express.static(__dirname + "/public/js"));
app.use(express.static(__dirname + "/public/css"));
app.use(express.static(__dirname + "/public/media"));
app.engine("html", require("ejs").renderFile);

// LOAD ROUTES
require("./server/routes/index")(app);
require("./server/routes/edit")(app);
require("./server/routes/dev")(app);
require("./server/routes/stat")(app);
require("./server/routes/contacts")(app);
require("./server/routes/remarks")(app);

Example of a route (edit.js)

'use strict';

module.exports = function(app) {

    app.get("/edit", function (req, res) {
        res.render("edit.html");
    });

};

Trying to access the HTML file by navigating to the website/edit route yield an 500 internal server error

Error: Failed to lookup view "edit.html" in views directory "C:\Users\andersl\Desktop\informr-test/views" at Function.app.render (C:\Users\andersl\Desktop\informr-test\node_modules\express\lib\application.js:493:17) at ServerResponse.res.render (C:\Users\andersl\Desktop\informr-test\node_modules\express\lib\response.js:798:7) at C:\Users\andersl\Desktop\informr-test\server\routes\edit.js:6:13 at callbacks (C:\Users\andersl\Desktop\informr-test\node_modules\express\lib\router\index.js:164:37) at param (C:\Users\andersl\Desktop\informr-test\node_modules\express\lib\router\index.js:138:11) at pass (C:\Users\andersl\Desktop\informr-test\node_modules\express\lib\router\index.js:145:5) at Router._dispatch (C:\Users\andersl\Desktop\informr-test\node_modules\express\lib\router\index.js:173:5) at Object.router (C:\Users\andersl\Desktop\informr-test\node_modules\express\lib\router\index.js:33:10) at next (C:\Users\andersl\Desktop\informr-test\node_modules\express\node_modules\connect\lib\proto.js:193:15) at SendStream.error (C:\Users\andersl\Desktop\informr-test\node_modules\express\node_modules\connect\node_modules\serve-static\index.js:74:37)

The following app.use combinations are also unsuccessful:

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

The weird thing is that index.html works fine, but only that route.

My app is structured as such:

server.js
/public
  /views - all html files
  /js
  /css
  /media
/server
  /routes
  etc...

What is it I don't understand, and what is the solution?

Thanks.

Upvotes: 0

Views: 1511

Answers (1)

mupersan82
mupersan82

Reputation: 567

Setting the views path was the solution.

app.set('views', __dirname + '/public/views');

Upvotes: 2

Related Questions