connect-src 限制下 fetch 请求被拦截怎么办?
我在项目里加了 CSP 的 connect-src 策略,只允许请求自家的 API 域名,但本地开发时用 fetch 调用 localhost:3001 的 mock 接口就被浏览器拦了。控制台报错:Refused to connect to ‘http://localhost:3001/api/data’ because it violates the CSP directive: connect-src ‘self’。
我试过在 meta 标签里加 localhost,但好像没生效。是不是写法不对?下面是我在 React 组件里发起请求的代码:
useEffect(() => {
fetch('http://localhost:3001/api/data')
.then(res => res.json())
.then(data => setData(data))
.catch(err => console.error(err));
}, []);
<meta http-equiv="Content-Security-Policy" content="connect-src 'self' http://localhost:3001">就行了。记得清理浏览器缓存再试。