Node.js + Express without using Jade

前端 未结 6 1499
礼貌的吻别
礼貌的吻别 2020-12-13 04:15

Is it possible to use express without any template engine?

相关标签:
6条回答
  • 2020-12-13 04:22

    Yes,

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

    should just work

    0 讨论(0)
  • 2020-12-13 04:22

    This is all out of date - correct answer for 3x, 4x is

    The second answer here: Render basic HTML view?

    0 讨论(0)
  • 2020-12-13 04:26

    For anyone having the need to immediately use regular HTML without jade in a new express project, you can do this.

    Add a index.html to the views folder.

    In app.js change

    app.get('/', routes.index);
    

    to

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

    UPDATE

    Use this instead. See comment section below for explanation.

    app.get('/', function(req, res) {
      res.sendFile(__dirname + "/views/index.html"); 
    });
    
    0 讨论(0)
  • 2020-12-13 04:36

    You can serve static files automatically with Express like this:

    // define static files somewhere on top
    app.use(express['static'](__dirname + '/your_subdir_with_html_files'));
    

    Actually this should be express.static(...) but to pass JSLint above version works too ;)

    Then you start the server and listen e.g. on port 1337:

    // app listens on this port
    app.listen(1337);
    

    Express now serves static files in /your_subdir_with_html_files automatically like this:

    http://localhost:1337/index.html

    http://localhost:1337/otherpage.html

    0 讨论(0)
  • 2020-12-13 04:37

    UPDATED

    Some might have concerns that sendFile only provides client side caching. There are various ways to have server side caching and keeping inline with the OP's question one can send back just text too with send:

    res.send(cache.get(key));
    

    Below was the original answer from 3+ years ago:

    For anyone looking for an alternative answer to PavingWays, one can also do:

    app.get('/', function(req, res) {
      res.sendFile('path/to/index.html');
    });
    

    With no need to write:

    app.use(express['static'](__dirname + '/public'));
    
    0 讨论(0)
  • 2020-12-13 04:37

    In your main file:

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

    Your index.jade file should only contain:

    include index.html
    

    where index.html is the raw HTML you made.

    0 讨论(0)
提交回复
热议问题