简体   繁体   中英

How can I use Express and EJS to serve static and dynamic content?

I want to build a simple app using node.js that 'functions' like IIS/classic ASP where all the content (html, png, js, css, ejs) can be in one directory and the ejs file uses javascript vs. VBScript.

I've gathered the following from API's and other examples, but the ejs file arrives at the browser as a binary and gets saved....

My node.js file:

var express = require('express');
var app = express();
app.use(app.router);
app.use(express.static(__dirname + '/html')); 
app.engine('.ejs', require('ejs').__express);
app.set('views', __dirname + '/html');
app.set('view engine', 'ejs');
app.get('*.ejs', function(req, res) {
   res.render(__dirname + '/html' + req.url, function(err, result) {
      res.end(result);
   });
});
app.listen(8080);

My test.ejs file:

<!DOCTYPE html>
<html>
   <head><title>A test</title></head>
   <body>
     My Test Page
       <% if (1==1) { %>
          Working
       <%}%>
   </body>
</html>​

What am I missing or where can I find a working example?

I FIGURED IT OUT... SOLUTION ADDED ABOVE

express.js won't magically try to render static files, you have to explicitly call render somewhere.

I believe something like this would work:

var express = require('express')
var app = express()
app.engine('.ejs', require('ejs').__express)
app.set('views', __dirname + '/html')
app.set('view engine', 'ejs')
app.use(app.router) // only in express 3, remove that in express 4
app.get('/test.html', function(req, res, next) {
    res.render('test.ejs')
})
app.use(express.static(__dirname + '/html'))
app.listen(8080)

I believe is not necessary to run render in every place, I use this example to render my static content by migrating express 2.3.7 to 4 and works fine with :

app.engine('.ejs', require('ejs').__express);
app.set('views', __dirname + '/public')
app.set('view engine', 'ejs')

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

My static content is in 'public' directory.

I just want to add that express supports EJS out of the box these days:

https://expressjs.com/en/starter/generator.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM