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

对接Squarespace API时main.js加载MIME类型错误求助

问题核心

浏览器拒绝执行main.js的原因是:服务器返回该文件时,MIME类型是text/html而非正确的application/javascript。通常是因为服务器找不到main.js,返回了HTML格式的404页面或默认页面。

解决办法及代码修正

1. 确保服务器正确处理静态文件

如果用原生Node.js写服务器,必须手动配置静态文件路由并指定正确的MIME类型。以下是修正后的server.mjs示例:

import { createServer } from 'http';
import { readFile, stat } from 'fs/promises';
import { join, extname } from 'path';

const PORT = 3000;
// 假设静态文件(index.html、main.js)都放在public文件夹下
const publicFolder = join(process.cwd(), 'public');

// 配置常见文件的MIME类型映射
const mimeMap = {
  '.html': 'text/html',
  '.js': 'application/javascript',
  '.css': 'text/css'
};

const server = createServer(async (req, res) => {
  // 处理根路径请求,默认返回index.html
  let targetPath = join(publicFolder, req.url === '/' ? 'index.html' : req.url);

  try {
    const fileInfo = await stat(targetPath);
    // 如果请求的是目录,自动查找目录下的index.html
    if (fileInfo.isDirectory()) {
      targetPath = join(targetPath, 'index.html');
    }

    // 根据文件后缀匹配对应MIME类型
    const fileExt = extname(targetPath);
    const contentType = mimeMap[fileExt] || 'application/octet-stream';

    // 读取文件并返回给浏览器
    const fileContent = await readFile(targetPath);
    res.writeHead(200, { 'Content-Type': contentType });
    res.end(fileContent);
  } catch (error) {
    // 处理文件不存在的情况,返回404页面
    res.writeHead(404, { 'Content-Type': 'text/html' });
    res.end('<h1>404 文件未找到</h1>');
  }
});

server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

2. 确认HTML中脚本路径正确

检查index.html里的script标签,确保路径和文件实际位置匹配:

<!-- 如果main.js和index.html在同一目录,用相对路径即可 -->
<script src="./main.js"></script>

3. 核对文件目录结构

确保项目文件摆放正确,示例结构:

你的项目文件夹
├── server.mjs
└── public
    ├── index.html
    └── main.js
验证方法

启动服务器后,直接在浏览器地址栏输入http://localhost:3000/main.js,如果能看到main.js里的代码,说明服务器已经正确返回JS文件,MIME类型也配置正确,再刷新页面就不会报错了。

内容的提问来源于stack exchange,提问作者Joshua Crocker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:36:15