Render basic HTML view?

2019-01-01 06:52发布

问题:

I have a basic node.js app that I am trying to get off the ground using Express framework. I have a views folder where I have an index.html file. But I receive the following error when loading the web browser.

Error: Cannot find module \'html\'

Below is my code.

var express = require(\'express\');
var app = express.createServer();

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

app.get(\'/\', function(req, res) {
    res.render(\'index.html\');
});

app.listen(8080, \'127.0.0.1\')

What am I missing here?

回答1:

You can have jade include a plain HTML page:

in views/index.jade

include plain.html

in views/plain.html

<!DOCTYPE html>
...

and app.js can still just render jade:

res.render(index)


回答2:

Many of these answers are out of date.

Using express 3.0.0 and 3.1.0, the following works:

app.set(\'views\', __dirname + \'/views\');
app.engine(\'html\', require(\'ejs\').renderFile);

See the comments below for alternative syntax and caveats for express 3.4+:

app.set(\'view engine\', \'ejs\');

Then you can do something like:

app.get(\'/about\', function (req, res)
{
    res.render(\'about.html\');
});

This assumes you have your views in the views subfolder, and that you have installed the ejs node module. If not, run the following on a Node console:

npm install ejs --save


回答3:

From the Express.js Guide: View Rendering

View filenames take the form Express.ENGINE, where ENGINE is the name of the module that will be required. For example the view layout.ejs will tell the view system to require(\'ejs\'), the module being loaded must export the method exports.render(str, options) to comply with Express, however app.register() can be used to map engines to file extensions, so that for example foo.html can be rendered by jade.

So either you create your own simple renderer or you just use jade:

 app.register(\'.html\', require(\'jade\'));

More about app.register.

Note that in Express 3, this method is renamed app.engine



回答4:

try this. it works for me.

app.configure(function(){

  .....

  // disable layout
  app.set(\"view options\", {layout: false});

  // make a custom html template
  app.register(\'.html\', {
    compile: function(str, options){
      return function(locals){
        return str;
      };
    }
  });
});

....

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


回答5:

You could also read the html file and send it.

app.get(\'/\', function(req, res) {
    fs.readFile(__dirname + \'/public/index.html\', \'utf8\', function(err, text){
        res.send(text);
    });
});


回答6:

If you\'re using express@~3.0.0 change the line below from your example:

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

to something like this:

app.set(\"view options\", {layout: false});
app.use(express.static(__dirname + \'/public\'));

I made it as described on express api page and it works like charm. With that setup you don\'t have to write additional code so it becomes easy enough to use for your micro production or testing.

Full code listed below:

var express = require(\'express\');
var app = express.createServer();

app.set(\"view options\", {layout: false});
app.use(express.static(__dirname + \'/public\'));

app.get(\'/\', function(req, res) {
    res.render(\'index.html\');
});

app.listen(8080, \'127.0.0.1\')


回答7:

app.get(\'/\', function (req, res) {
res.sendfile(__dirname + \'/public/index.html\');
});


回答8:

I also faced the same issue in express 3.X and node 0.6.16. The above given solution will not work for latest version express 3.x. They removed the app.register method and added app.engine method. If you tried the above solution you may end up with the following error.

node.js:201
        throw e; // process.nextTick error, or \'error\' event on first tick
              ^
TypeError: Object function app(req, res){ app.handle(req, res); } has no method \'register\'
    at Function.<anonymous> (/home/user1/ArunKumar/firstExpress/app.js:37:5)
    at Function.configure (/home/user1/ArunKumar/firstExpress/node_modules/express/lib/application.js:399:61)
    at Object.<anonymous> (/home/user1/ArunKumar/firstExpress/app.js:22:5)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:40)

To get rid of the error message. Add the following line to your app.configure function

app.engine(\'html\', require(\'ejs\').renderFile);

Note: you have to install ejs template engine

npm install -g ejs

Example:

app.configure(function(){

  .....

  // disable layout
  app.set(\"view options\", {layout: false});

  app.engine(\'html\', require(\'ejs\').renderFile);

....

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

Note: The simplest solution is to use ejs template as view engine. There you can write raw HTML in *.ejs view files.



回答9:

If you don\'t have to use the views directory, Simply move html files to the public directory below.

and then, add this line into app.configure instead of \'/views\'.

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


回答10:

folder structure:

.
├── index.html
├── node_modules
│   ├──{...}
└── server.js

server.js

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

app.use(express.static(\'./\'));

app.get(\'/\', function(req, res) {
    res.render(\'index.html\');
});

app.listen(8882, \'127.0.0.1\')

index.html

<!DOCTYPE html>
<html>
<body>

<div> hello world </div>

</body>
</html>

output:

hello world



回答11:

For my project I have created this structure:

index.js
css/
    reset.css
html/
    index.html

This code serves index.html for / requests, and reset.css for /css/reset.css requests. Simple enough, and the best part is that it automatically adds cache headers.

var express = require(\'express\'),
    server = express();

server.configure(function () {
    server.use(\'/css\', express.static(__dirname + \'/css\'));
    server.use(express.static(__dirname + \'/html\'));
});

server.listen(1337);


回答12:

With Express 4.0.0, the only thing you have to do is comment out 2 lines in app.js:

/* app.set(\'views\', path.join(__dirname, \'views\'));
app.set(\'view engine\', \'jade\'); */ //or whatever the templating engine is.

And then drop your static file into the /public directory. Example: /public/index.html



回答13:

I added below 2 line and it work for me

    app.set(\'view engine\', \'html\');
    app.engine(\'html\', require(\'ejs\').renderFile);


回答14:

Try res.sendFile() function in Express routes.

var express = require(\"express\");
var app     = express();
var path    = require(\"path\");


app.get(\'/\',function(req,res){
  res.sendFile(path.join(__dirname+\'/index.html\'));
  //__dirname : It will resolve to your project folder.
});

app.get(\'/about\',function(req,res){
  res.sendFile(path.join(__dirname+\'/about.html\'));
});

app.get(\'/sitemap\',function(req,res){
  res.sendFile(path.join(__dirname+\'/sitemap.html\'));
});

app.listen(3000);

console.log(\"Running at Port 3000\");

Read here : http://codeforgeek.com/2015/01/render-html-file-expressjs/



回答15:

I didn\'t want to depend on ejs for simply delivering an HTML file, so I simply wrote the tiny renderer myself:

const Promise = require( \"bluebird\" );
const fs      = Promise.promisifyAll( require( \"fs\" ) );

app.set( \"view engine\", \"html\" );
app.engine( \".html\", ( filename, request, done ) => {
    fs.readFileAsync( filename, \"utf-8\" )
        .then( html => done( null, html ) )
        .catch( done );
} );


回答16:

To render Html page in node try the following,

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

app.engine(\'html\', require(\'ejs\').renderFile);
  • You need to install ejs module through npm like:

       npm install ejs --save
    


回答17:


1) The best way is to set static folder. In your main file (app.js | server.js | ???):

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

public/css/form.html
public/css/style.css

Then you got static file from \"public\" folder:

http://YOUR_DOMAIN/form.html
http://YOUR_DOMAIN/css/style.css

2)

You can create your file cache.
Use method fs.readFileSync

var cache = {};
cache[\"index.html\"] = fs.readFileSync( __dirname + \'/public/form.html\');

app.get(\'/\', function(req, res){    
    res.setHeader(\'Content-Type\', \'text/html\');
    res.send( cache[\"index.html\"] );                                
};);


回答18:

I was trying to set up an angular app with an express RESTful API and landed on this page multiple times though it wasn\'t helpful. Here\'s what I found that worked:

app.configure(function() {
    app.use(express.static(__dirname + \'/public\'));         // set the static files location
    app.use(express.logger(\'dev\'));                         // log every request to the console
    app.use(express.bodyParser());                          // pull information from html in POST
    app.use(express.methodOverride());                      // simulate DELETE and PUT
    app.use(express.favicon(__dirname + \'/public/img/favicon.ico\'));
});

Then in the callback for your api routes look like: res.jsonp(users);

Your client side framework can handle routing. Express is for serving the API.

My home route looks like this:

app.get(\'/*\', function(req, res) {
    res.sendfile(\'./public/index.html\'); // load the single view file (angular will handle the page changes on the front-end)
});


回答19:

res.sendFile(__dirname + \'/public/login.html\');


回答20:

Here is a full file demo of express server!

https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906

hope it will help for you!

// simple express server for HTML pages!
// ES6 style

const express = require(\'express\');
const fs = require(\'fs\');
const hostname = \'127.0.0.1\';
const port = 3000;
const app = express();

let cache = [];// Array is OK!
cache[0] = fs.readFileSync( __dirname + \'/index.html\');
cache[1] = fs.readFileSync( __dirname + \'/views/testview.html\');

app.get(\'/\', (req, res) => {
    res.setHeader(\'Content-Type\', \'text/html\');
    res.send( cache[0] );
});

app.get(\'/test\', (req, res) => {
    res.setHeader(\'Content-Type\', \'text/html\');
    res.send( cache[1] );
});

app.listen(port, () => {
    console.log(`
        Server is running at http://${hostname}:${port}/ 
        Server hostname ${hostname} is listening on port ${port}!
    `);
});



回答21:

Add the following Lines to your code

  1. Replace \"jade\" with \"ejs\" & \"X.Y.Z\"(version) with \"*\" in package.json file

      \"dependencies\": {
       \"ejs\": \"*\"
      }
    
  2. Then in your app.js File Add following Code :

    app.engine(\'html\', require(\'ejs\').renderFile);

    app.set(\'view engine\', \'html\');

  3. And Remember Keep All .HTML files in views Folder

Cheers :)



回答22:

app.get(\'/\', function(req, res, next) {
    res.send(`<html><body><h1>My Server</h1></body></html>\')
});


回答23:

I wanted to allow requests to \"/\" to be handled by an Express route where previously they had been handled by the statics middleware. This would allow me to render the regular version of index.html or a version that loaded concatenated + minified JS and CSS, depending on application settings. Inspired by Andrew Homeyer\'s answer, I decided to drag my HTML files - unmodified - into a views folder, configure Express like so

   app.engine(\'html\', swig.renderFile);
   app.set(\'view engine\', \'html\');
   app.set(\'views\', __dirname + \'/views\');  

And created a route handler like so

 app.route(\'/\')
        .get(function(req, res){
            if(config.useConcatendatedFiles){
                return res.render(\'index-dist\');
            }
            res.render(\'index\');       
        });

This worked out pretty well.



回答24:

In server.js, please include

var express = require(\"express\");
var app     = express();
var path    = require(\"path\");


app.get(\'/\',function(req,res){
  res.sendFile(path.join(__dirname+\'/index.html\'));
  //__dirname : It will resolve to your project folder.
});


回答25:

I usually use this

app.configure(function() {
    app.use(express.static(__dirname + \'/web\'));
});

Just be careful because that\'ll share anything in the /web directory.

I hope it helps



回答26:

if you are using express framework to node.js

install npm ejs

then add config file

app.set(\'port\', process.env.PORT || 3000);
app.set(\'views\', __dirname + \'/views\');
app.set(\'view engine\', \'ejs\');
app.set(\'view engine\', \'jade\');
app.use(express.favicon());
app.use(express.logger(\'dev\'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router)

;

render the page from exports module form.js have the html file in the views dir with extension of ejs file name as form.html.ejs

then create the form.js

res.render(\'form.html.ejs\');