nodejs将html文件发送给客户端 [英] nodejs send html file to client

查看:174
本文介绍了nodejs将html文件发送给客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个功能将html文件发送给客户端,但是在客户端中我什么都没有(空白页),没有错误。有什么问题,请帮忙?

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);

我的test.html文件

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>


推荐答案

尝试这样的代码:

var app = express();
app.get('/test', function(req, res) {
    res.sendFile('views/test.html', {root: __dirname })
});




  1. 使用 res.sendFile ,而不是手动读取文件,以便express可以正确为您设置内容类型。

  1. Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.

您不需要 app.engine 行,因为它是由express内部处理的。

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

这篇关于nodejs将html文件发送给客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆