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

动态导入JSON文件时添加assert断言触发MIME类型错误的解决方法

动态导入JSON文件的问题解决办法

问题原因

  • 加assert: {type: 'json'}时,浏览器会将请求视为ES模块加载,要求服务器返回符合模块规范的MIME类型(如application/javascript),但服务器返回的是application/json,触发严格MIME类型检查报错。
  • 移除断言后,JSON文件被当作ES模块加载,实际的JSON内容会作为模块的default导出,所以直接打印模块对象只能看到Module {Symbol(Symbol.toStringTag): 'Module'}。

解决方法

1. 提取模块的default属性(无需修改服务器)

这是最直接的方案,移除断言后,从返回的模块对象中获取default属性即可拿到JSON内容:

let filePath = "../../mapping_data_files/contactMapping.json";
import(filePath).then(module => {
    const jsonData = module.default;
    console.log(jsonData);
});

2. 配置服务器适配assert断言(需要服务器权限)

如果一定要使用assert语法,需要让服务器返回JSON文件时,将Content-Type设置为application/javascript(或确保服务器支持JSON模块的MIME类型解析):

  • 比如Nginx:在配置文件中添加对应规则,指定该JSON文件的MIME类型为application/javascript
  • 比如Node.js Express:通过中间件修改响应头:
app.get('*.json', (req, res, next) => {
    res.setHeader('Content-Type', 'application/javascript');
    next();
});

3. 改用fetch API加载JSON(通用方案)

如果动态导入的方式受限于服务器配置,直接用fetch加载JSON是更通用的选择,无需依赖ES模块规则:

let filePath = "../../mapping_data_files/contactMapping.json";
fetch(filePath)
    .then(res => res.json())
    .then(jsonData => console.log(jsonData))
    .catch(err => console.error('加载失败:', err));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:05:14