客户端请求服务端JSON触发SyntaxError: Unexpected end of input问题排查
客户端请求JSON触发SyntaxError: Unexpected end of input问题
问题描述
客户端向服务器请求目录列表,服务器返回JSON文件,但客户端触发错误SyntaxError: Unexpected end of input。服务器日志显示文件已成功发送,手动通过网页访问服务器可获取有效JSON(已在线验证),请问这是客户端的问题吗?
服务端代码
app.get('/votes', (req, res) => { fs.readFile(path.resolve(__dirname, 'testing.json'), (err, data) => { if (err) { res.status(500).send('Error reading file'); } else { res.status(200).json(JSON.parse(data)); } }); });
客户端代码
async function dataFetch() { await fetch('https://serverIP/votes', { method: 'GET', mode: "no-cors", headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { console.log(`${data} <-- data`); jsonFile = data; }) .catch(error => { alert("an error has occured: "+error) console.log(`Error: ${error}`); }
已尝试其他请求方法,但均未成功。
问题原因及解决方案
1. 核心问题:mode: "no-cors"的限制
当设置mode: "no-cors"时,浏览器会强制限制对响应内容的访问——你无法读取响应的body、headers等任何数据,此时调用response.json()自然会失败,因为没有可解析的内容,进而抛出Unexpected end of input错误。
解决办法:移除mode: "no-cors"配置,改用默认的cors模式;如果服务端未配置跨域支持,需要在服务端添加CORS中间件(比如Express的cors包)来允许跨域请求。
2. 服务端代码优化
服务端中res.json(JSON.parse(data))属于多余操作,res.json()方法可以直接接收字符串格式的JSON,会自动完成解析并设置正确的Content-Type响应头,优化后代码更简洁:
app.get('/votes', (req, res) => { fs.readFile(path.resolve(__dirname, 'testing.json'), (err, data) => { if (err) { res.status(500).send('Error reading file'); } else { res.status(200).json(data); } }); });
3. 客户端代码修复
- 避免
async/await与.then()混用,保持代码风格统一; - 补全
catch块的闭合括号; - GET请求无需设置
Content-Type头(该头用于告知服务器请求body的格式,GET请求无body)。
优化后的客户端代码:
async function dataFetch() { try { const response = await fetch('https://serverIP/votes'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log(`${data} <-- data`); jsonFile = data; } catch (error) { alert("an error has occured: " + error); console.log(`Error: ${error}`); } }
内容的提问来源于stack exchange,提问作者Max Lebedev
相关产品推荐
相关产品推荐

