nodejs send html file to client

倖福魔咒の 提交于 2019-11-30 10:35:22

问题


I use this function to send html file to client, but in client I get nothing (blank page) without error. Something I wrong?, please help?

var express = require('express'); 
var fs = require('fs');
var app = express();
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express); 
    app.get('/test', function(req, res) {
            fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
                res.send(text);
            });
var port = process.env.PORT || 80;
var server = app.listen(port);
console.log('Express app started on port ' + port);

My test.html file

<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <style something here </style>
      <title>Test</title>
      <script src="..."></script>
   </head>
<body>
    <div> Somthing here </div>

    <script type="text/javascript">
        //something here
    </script>
</body></html>

回答1:


Try your code like this:

var app = express();
app.get('/test', function(req, res) {
    res.sendFile('views/test.html', {root: __dirname })
});
  1. Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.

  2. You don't need the app.engine line, as that is handled internally by express.




回答2:


After years, I want to add another approach by using a view engine in Express.js

var fs = require('fs');

app.get('/test', function(req, res, next) {
    var html = fs.readFileSync('./html/test.html', 'utf8')
    res.render('test', { html: html })
    // or res.send(html)
})

Then, do that in your views/test if you choose res.render method at the above code (I'm writing in EJS format):

<%- locals.html %>

That's all.

In this way, you don't need to break your View Engine arrangements.




回答3:


you can render page in express more easily

var app   = require('express')();        //to install express write "npm install express"

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

 res.sendFile(path.join(__dirname+'/signup.html'));

});

so if u request like http://127.0.0.1:8080/signup that it will render signup.html page



来源:https://stackoverflow.com/questions/20345936/nodejs-send-html-file-to-client

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