Node.js 的 HTTPS 服务器可以轻松访问静态页面内容,例如 HTML、CSS 和 JavaScript 文件。你可以使用 Node.js 内置的 fs 模块读取这些文件,然后将其发送到客户端。在发送静态文件之前,需要设置正确的 MIME 类型和 HTTP 头文件,以确保客户端正确解析文件。

以下是一个简单的示例:

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

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

const server = https.createServer(options, (req, res) => {
  if (req.url === '/') {
    const file = fs.readFileSync('index.html', 'utf8');
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(file);
  } else if (req.url === '/style.css') {
    const file = fs.readFileSync('style.css', 'utf8');
    res.writeHead(200, { 'Content-Type': 'text/css' });
    res.end(file);
  } else if (req.url === '/script.js') {
    const file = fs.readFileSync('script.js', 'utf8');
    res.writeHead(200, { 'Content-Type': 'text/javascript' });
    res.end(file);
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('404 Not Found');
  }
});

server.listen(443, () => {
  console.log('Server running on port 443');
});

该示例创建了一个 HTTPS 服务器,并检查客户端请求的 URL。如果 URL 是根路径 /,则读取并发送 index.html 文件;如果 URL 是 /style.css,则读取并发送 style.css 文件;如果 URL 是 /script.js,则读取并发送 script.js 文件。如果 URL 不是这些路径中的任何一个,则返回 404 错误。

请注意,该示例仅用于演示目的,实际应用中需要更复杂的处理程序来处理静态文件请求,并确保安全性和性能。

Node.js HTTPS 服务器:如何访问静态页面

原文地址: https://www.cveoy.top/t/topic/nNO1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录