StencilJS+Ionic开发:API请求JSON解析报错求助
问题原因与解决方案
核心问题:no-cors模式导致无法读取响应内容
你在fetch请求里设置了mode: 'no-cors',这种模式下浏览器会限制对响应内容的访问,返回的是不透明响应(opaque response),完全无法读取响应体。这就是调用response.json()时出现「Unexpected end of input」的根本原因——没有可解析的JSON数据。
修复步骤:
移除
mode: 'no-cors'配置
修改fetch请求代码,删掉mode: 'no-cors'这一行,让浏览器默认使用cors模式:const response = await fetch(`http://localhost:3000/api/${userIDSTR}`, { method: 'GET' // 去掉mode: 'no-cors'配置 });在Express API中配置CORS
本地跨域请求需要后端允许前端域名访问,安装cors中间件并配置:npm install cors在Express入口文件(如
app.js)中添加:const cors = require('cors'); // 允许你的Stencil前端域名(默认是http://localhost:3333) app.use(cors({ origin: 'http://localhost:3333' })); // 若要允许所有本地开发域名,可简化为:app.use(cors());添加错误处理逻辑
为避免未捕获的Promise错误,给fetch和JSON解析加上try/catch:async handleSubmit(event: Event) { event.preventDefault(); const userIDGathered = this.textInput.value; const userIDSTR = userIDGathered.toString(); if (!userIDSTR.trim()) { console.log('请输入有效的用户ID'); return; } try { const response = await fetch(`http://localhost:3000/api/${userIDSTR}`, { method: 'GET' }); if (!response.ok) { throw new Error(`请求失败:${response.status}`); } const data = await response.json(); console.log(data); } catch (error) { console.error('请求或解析错误:', error); } }验证API响应格式
确保你的Express API返回有效的JSON格式数据,示例路由:app.get('/api/:userId', (req, res) => { const userId = req.params.userId; // 返回标准JSON结构 res.json({ id: userId, name: '示例用户', info: '测试数据' }); });
额外提示
- 检查Stencil应用的运行端口(默认3333),确保CORS配置中的
origin与实际端口一致。 - 先通过浏览器直接访问
http://localhost:3000/api/你的用户ID,确认API确实返回有效JSON。
内容的提问来源于stack exchange,提问作者Kyle Styx
相关产品推荐
相关产品推荐

