HTTPS使用Node Js呈现html文件

时间:2017-10-14 19:31:28

标签: node.js https

我尝试在localhost中设置HTTPS服务器,但是我不知道在服务器运行时如何呈现html文件。以下是我的代码:

var https = require('https'); var fs = require('fs');

var options = {   key: fs.readFileSync('client-key.pem'),   
                 cert: fs.readFileSync('client-cert.pem') };

var a = https.createServer(options, function (req, res) {   
        console.log('Server is starting');           
       res.writeHead(200);                                            
    // res.end("hello world\n");
       res.render('index.html');

}).listen(8000);

我可以访问localhost,但每当我尝试渲染html文件时,都会收到错误消息' .render()不是函数'有什么替代' ;调用'服务器运行时的html文件。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:3)

您需要使用文件系统。 这样您就可以准备文件,将其存储在content内并将完整的html文件发送到您的客户端

var fs = require('fs');

fs.readFile('./index.html', function (error, content) {
   if (error) {
      response.writeHead(500);
      response.end('Error');
   } else {
      response.writeHead(200, { 'Content-Type': 'text/html' });
      response.end(content, 'utf-8');
   }
});

您在pure nodejs中没有render函数。如果你想使用它,你必须使用expressjs。

我写的代码需要在你createServer函数

里面