gpt4 book ai didi

node.js - HTTPS 使用 Node Js 渲染 html 文件

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:13 24 4
gpt4 key购买 nike

我尝试在本地主机中设置 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);

我可以访问本地主机,但是每当我尝试渲染 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');
}
});

纯 Node.js 中没有 render 函数。如果你想使用它,你需要使用express.js。

我编写的代码需要位于您的 createServer 函数内。

关于node.js - HTTPS 使用 Node Js 渲染 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46748539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com