【问题标题】:Node.js quick file server (static files over HTTPS)Node.js 快速文件服务器(通过 HTTPS 的静态文件)
【发布时间】:2020-03-15 17:58:48
【问题描述】:

我已经成功地使用 node.js 应用程序中的这些命令创建了带有 node 的 https 服务器:

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

var httpsOptions = {
    key: fs.readFileSync('path/to/server-key.pem'),
    cert: fs.readFileSync('path/to/server-crt.pem')
};

var app = function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}

http.createServer(app).listen(8888);
https.createServer(httpsOptions, app).listen(4433);

我想做的是让 https 服务器从文件夹运行,类似于this,它是用于 http-server。因此,如果我稍后在 https 文件夹中添加文件,则可以从 https://localhost:4433/main.js 轻松访问文件(main.js 只是一个示例文件)。是否可以为 https 做到这一点?

【问题讨论】:

    标签: node.js https fileserver


    【解决方案1】:

    是的,有可能。

    参考这个答案npm http-server with SSL

    第 1 步。 编写服务器

    您可以使用纯 node.js 模块来提供静态文件,也可以使用 express 框架来解决您的问题。 https://expressjs.com/en/starter/static-files.html

    第 2 步。 编写命令行脚本

    您必须编写一个脚本并最好保存到 bin 文件夹中,该文件夹接受诸如文件夹路径、端口等命令行参数并启动服务器。此外,您可以使用node.js 使用commander.js 等编写此类脚本。

    【讨论】:

    • 你回答的第一个链接做到了,而且很简单:http-server -S -a localhost -p 442 -C certificate.pem -K privatekey.pem
    【解决方案2】:
    1. 在请求中查找 URL
    2. 使 URL 成为您的文件夹文件路径
    3. 通过文件路径读取文件数据
    4. 响应文件数据

    例如,如果您的文件夹有 1.txt 2.html

    • localhost:8000/1.txt 会得到 1.txt
    • localhost:8000/2.html 将获得 2.html
    const http = require('http')
    const fs = require('fs')
    const path = require('path');
    
    const server = http.createServer((req, res) => {  
      var filePath = path.join('.',req.url)
      // Browser will autorequest 'localhost:8000/favicon.ico'
      if ( !(filePath == "favicon.ico") ) {
        file = fs.readFileSync(filePath,'utf-8')
        res.write(file)
      }
      res.end();
    });
    
    server.listen(8000);
    

    【讨论】:

      猜你喜欢
      • 2013-04-26
      • 1970-01-01
      • 2018-05-14
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多