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

FireFox从本地服务器获取JSON数组遇CSP/NetworkError问题求助

解决FireFox中Fetch请求被Content Security Policy阻止的问题

问题场景

我尝试用以下代码获取http://localhost:5000/posts的JSON数据:

fetch('/posts')
  .then(res => res.json())
  .then(resBody => console.log(resBody));

在FireFox开发者控制台中收到错误:

Content Security Policy: The page's settings blocked the loading of a resource at http://localhost:5000/posts ("default-src").

Promise { <state>: "rejected", <reason>: TypeError }
​
<state>: "rejected"
​
<reason>: TypeError: NetworkError when attempting to fetch resource.
​
<prototype>: Promise.prototype { … }

但用Postman可以正常获取数据,返回结果如下:

[{"postId":1,"message":"Hello World!"},{"postId":2,"message":"Ciao!"}]

Postman也能正常发送POST请求添加数据,问题仅出现在FireFox浏览器中。

问题原因

这是Content Security Policy (CSP) 浏览器安全机制导致的:

  • CSP会限制页面能加载的资源来源,错误里的default-src说明当前页面的默认规则不允许请求localhost:5000这个源。
  • Postman这类API工具不受浏览器的CSP规则约束,所以能正常访问接口。

解决方案

1. 配置服务器端CSP响应头(推荐生产环境使用)

如果你的服务器是Node.js/Express,可以通过以下方式修改CSP规则:

  • 方式一:手动设置响应头,允许localhost:5000的请求
app.use((req, res, next) => {
  // default-src允许自身域名和localhost:5000
  res.setHeader(
    'Content-Security-Policy',
    'default-src \'self\' http://localhost:5000'
  );
  next();
});
  • 方式二:更精细控制,用connect-src专门限制Fetch/XHR的请求源
app.use((req, res, next) => {
  res.setHeader(
    'Content-Security-Policy',
    'default-src \'self\'; connect-src http://localhost:5000'
  );
  next();
});

2. 临时调试方案(仅用于本地调试)

在FireFox开发者工具中临时禁用CSP:

  • 打开开发者工具 → 点击右上角齿轮图标(设置) → 找到「高级」板块 → 勾选「禁用内容安全策略」

补充说明

如果服务器本身没配置CSP,那可能是页面所在的托管环境、浏览器扩展自动添加了CSP规则,可以在浏览器开发者工具的「网络」面板中,查看页面的响应头里的Content-Security-Policy字段,确认规则来源。

内容的提问来源于stack exchange,提问作者Timothy W. Times

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:10:50