Render raw HTML

前端 未结 11 1170
自闭症患者
自闭症患者 2020-12-23 18:48

I want to render raw .html pages using Express 3 as follows:

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

11条回答
  •  -上瘾入骨i
    2020-12-23 19:09

    What I think you are trying to say is: How can I serve static html files, right?

    Let's get down to it.

    First, some code from my own project:

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

    What this means that there is a folder named public inside my app folder. All my static content such as css, js and even html pages lie here.

    To actually send static html pages, just add this in your app file

    app.get('/', function(req, res) {
      res.sendFile(__dirname + '/public/layout.html');
    });
    

    So if you have a domain called xyz.com; whenever someone goes there, they will be served layout.html in their browsers.

    Edit

    If you are using express 4, things are a bit different. The routes and middleware are executed exactly in the same order they are placed.

    One good technique is the place the static file serving code right after all the standard routes. Like this :

    // All standard routes are above here
    app.post('/posts', handler.POST.getPosts);
    
    // Serve static files
    app.use(express.static('./public'));
    

    This is very important as it potentially removes a bottleneck in your code. Take a look at this stackoverflow answer(the first one where he talks about optimization)

    The other major change for express 4.0 is that you don't need to use app.configure()

提交回复
热议问题