HTTPS使用Node Js呈现html文件
问题描述:
我试图在localhost中设置HTTPS服务器,但是我不知道如何在服务器运行时呈现html文件。下面是我的代码:HTTPS使用Node Js呈现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);
我可以访问到本地主机,但每当我试图呈现一个HTML文件,我得到了一个错误信息“.render()是不是一个函数”,什么是另类在服务器运行时调用一个html文件。任何帮助表示赞赏!
答
你需要使用文件系统。 这样,您将准备好文件,它里面存储和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');
}
});
您不必在纯在的NodeJS功能render
。如果你想使用它,你可以使用expressjs。
我写的代码需要在里面你createServer
功能
嗨,这些代码工作对我来说,太感谢你了!谢谢!! – JackPowell