how can i render html file in node.js

感情迁移 提交于 2019-12-13 18:50:54

问题


i have tried to render html file but i got this error . i have login.html within public folder.how to render html file.thanks in advance.

my server side coding

var express = require('express');

var app = express();

app.configure(function(){

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

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


 });

app.get('/', function(req, res) {

    res.render('login.html');

});

app.listen(8000)

Error: Failed to lookup view "login.html"

at Function.render (/home/aware/local/src/node_modules/express/lib/application.js:493:17)
at ServerResponse.render (/home/aware/local/src/node_modules/express/lib/response.js:753:7)
at /home/aware/local/src/health/demo2.js:17:9
at callbacks (/home/aware/local/src/node_modules/express/lib/router/index.js:161:37)
at param (/home/aware/local/src/node_modules/express/lib/router/index.js:135:11)
at pass (/home/aware/local/src/node_modules/express/lib/router/index.js:142:5)
at Router._dispatch (/home/aware/local/src/node_modules/express/lib/router/index.js:170:5)
at Object.router [as handle] (/home/aware/local/src/node_modules/express/lib/router/index.js:33:10)
at next (/home/aware/local/src/node_modules/express/node_modules/connect/lib/proto.js:199:15)
at resume (/home/aware/local/src/node_modules/express/node_modules/connect/lib/middleware/static.js:60:7)

回答1:


The closest you can get to using html for node views is EJS (Embedded JavaScript)

This way you write your normal HTML, pass your data through node and display them using tags like: <%= var %>

http://embeddedjs.com/

https://github.com/visionmedia/ejs




回答2:


The files you keep inside your public folder will not be rendered because they are set as static, so they will be served as is. All other files outside of this will be rendered. Remember to set the rendering engine.




回答3:


I just came in contact with connect today & wanted to solve a simillar issue, serving a simple HTML file. In my case, I wanted to display a 404 when any previous middlewares hadn't finished the request.

I create a function, show404 and then you can do something like app.use(show404). Here's my CoffeScript for that mostly inspired in connect errorHandler source code.

show404 = (req, res, next) ->
    res.statusCode = 404
    res.setHeader 'Content-Type', 'text/html; charset=utf-8'
    html_path = require("path").resolve('.tmp/404.html')
    require('fs').readFile html_path, (err, data)->
        throw err if err
        console.log "DATA:", data
        res.end data


来源:https://stackoverflow.com/questions/15520212/how-can-i-render-html-file-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!