在Node.js后端使用Axios发起GET请求时遭遇'unexpected end of file'错误
解决Node.js中Axios请求返回'unexpected end of file'错误
问题场景
在基于Node.js的后端项目中使用Axios发起请求时,持续触发unexpected end of file错误,相关代码如下:
axios请求工具文件(utils/getData.js)
import axios from "axios"; export const getData = async () => { let data; try { const response = await axios.get( "https://jsonplaceholder.typicode.com/users" ); console.log(response); data = response; } catch (error) { console.log(error.message); return; } return data; };
服务入口文件(server.js)
import express from "express"; import cors from 'cors'; import axios from "axios"; import { getData } from "./utils/getData.js"; const app = express(); app.use(cors()); app.use(express.json()); app.get("/", async (req, res) => { let users; users = await getData(); res.send(users); }) app.listen(5000, () => { console.log("server listening at port 5000"); })
问题原因及修复方案
1. 核心问题:Axios响应对象无法被Express序列化
Axios返回的完整response对象包含大量不可序列化的属性(如请求配置、响应流、内部方法等),Express的res.send()在尝试将其转换为JSON时会失败,直接导致unexpected end of file错误。
修复代码:
修改getData函数,仅返回响应中的data字段(接口返回的实际业务数据):
export const getData = async () => { try { const response = await axios.get( "https://jsonplaceholder.typicode.com/users" ); console.log(response.data); return response.data; // 只返回实际数据 } catch (error) { console.log(error.message); return null; // 统一返回值类型,避免后续处理异常 } };
同时优化路由处理逻辑,使用res.json()更精准地返回JSON数据:
app.get("/", async (req, res) => { const users = await getData(); if (users) { res.json(users); } else { res.status(500).send("获取用户数据失败"); } })
2. 辅助优化:完善错误分支的返回逻辑
原代码中getData函数捕获错误后直接return,会导致路由中users变量为undefined,触发res.send(undefined)的响应异常。统一返回null后,可在路由中明确处理失败场景,避免响应中断。
3. 版本兼容性检查
确保项目package.json中添加了"type": "module"以支持ES模块语法,同时更新依赖到稳定版:
npm update axios express cors
内容的提问来源于stack exchange,提问作者AKHIL PANWAR
相关产品推荐
相关产品推荐

