You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTTPS服务器中外置script.js无法运行问题排查求助

问题描述

搭建了一个HTTPS服务器,除外置script.js无法运行外其余功能正常,将脚本改为内嵌形式则可正常工作。

相关代码

server.js

const https = require("https");
const fs = require("fs");
const options = {
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert'),
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end(fs.readFileSync('index.html'));
}).listen(8000, "localhost");

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
    <style></style>
  </head>

  <body>
    <button onclick="testFunc();" id="button1"></button>
    
    <script src="script.js"></script>
  </body>
</html>

script.js

var button1 = document.getElementById("button1");

alert(); //first alert

function testFunc() {
  alert(); //second alert
}

目前脚本完全无法运行,连第一个alert都不弹出,已确认文件名无误,请问原因是什么?该如何解决?


原因与解决方法

核心原因

你的HTTPS服务器只处理了根路径的请求(访问https://localhost:8000/时返回index.html),但当浏览器请求script.js时,服务器依然返回index.html的内容,导致浏览器解析非JS文件,脚本自然无法执行。

解决方法

修改server.js,根据请求的URL路径返回对应文件:

const https = require("https");
const fs = require("fs");
const path = require("path");

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

https.createServer(options, (req, res) => {
  // 确定请求的文件路径
  let filePath = "." + req.url;
  if (filePath === "./") {
    filePath = "./index.html";
  }

  // 根据文件后缀设置响应头的Content-Type
  const extname = path.extname(filePath);
  let contentType = "text/html";
  switch (extname) {
    case ".js":
      contentType = "text/javascript";
      break;
    case ".css":
      contentType = "text/css";
      break;
  }

  // 读取并返回对应文件
  fs.readFile(filePath, (error, content) => {
    if (error) {
      // 文件不存在时返回404
      res.writeHead(404);
      res.end("File not found");
    } else {
      res.writeHead(200, { "Content-Type": contentType });
      res.end(content, "utf-8");
    }
  });
}).listen(8000, "localhost");

说明

  • 新增path模块处理文件路径,根据请求URL判断要返回的目标文件
  • 针对不同文件类型设置正确的Content-Type,确保浏览器能正确解析JS文件
  • 处理了文件不存在的异常情况,返回404提示

内容的提问来源于stack exchange,提问作者Sc-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 17:58:18