Next.js 13 向本地Django服务(localhost:8001)发起Fetch请求失败求助
Next.js 13 本地Fetch请求Django服务失败(TypeError: fetch failed)解决方案
问题背景
在Next.js 13项目的RootLayout(服务器组件)中发起针对localhost:8001上Django服务的GET请求时,抛出TypeError: fetch failed错误,已开启Django的CORS(CORS_ORIGIN_ALLOW_ALL = True),且能正常请求公开API。
错误日志
TypeError: fetch failed at Object.processResponse (node:internal/deps/undici/undici:7188:34) at node:internal/deps/undici/undici:7516:42 at node:internal/process/task_queues:140:7 at AsyncResource.runInAsyncScope (node:async_hooks:202:9) at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { cause: Error: [object Object] at makeNetworkError (node:internal/deps/undici/undici:6317:51) at httpNetworkFetch (node:internal/deps/undici/undici:7810:16) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async httpNetworkOrCacheFetch (node:internal/deps/undici/undici:7703:33) at async httpFetch (node:internal/deps/undici/undici:7557:37) at async schemeFetch (node:internal/deps/undici/undici:7489:18) at async node:internal/deps/undici/undici:7342:20 at async mainFetch (node:internal/deps/undici/undici:7338:20) { [cause]: undefined } } TypeError: fetch failed at Object.processResponse (node:internal/deps/undici/undici:7188:34) at node:internal/deps/undici/undici:7516:42 at node:internal/process/task_queues:140:7 at AsyncResource.runInAsyncScope (node:async_hooks:202:9) at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { digest: '1117663215'
相关代码
import './globals.css' export default async function RootLayout({ children, }: { children: React.ReactNode }) { // const data = await fetch(`https://dummyjson.com/products/1`, { cache: 'force-cache' }); const data = await fetch(`http://localhost:8001/board/`, { method: 'GET', headers: { 'Accept': 'application/json', "Content-Type": "application/json" }, redirect: 'follow', cache: 'force-cache' }); console.log(data) return ( <html lang="en"> <head /> <body> <h1></h1> <div>{children}</div> </body> </html> ) }
解决步骤
1. 确认Django服务的可达性
- 直接在浏览器或Postman中访问
http://localhost:8001/board/,检查是否能返回正常的JSON响应。如果无法访问:- 确认Django服务是否已启动(执行
python manage.py runserver)。 - 检查Django的路由配置,确保
/board/路由存在且正确映射到视图。 - 查看Django的运行日志,排查服务端是否有报错。
- 确认Django服务是否已启动(执行
2. 处理服务器组件的网络环境差异
RootLayout是Next.js的服务器组件,fetch请求在Node.js环境中执行,而非浏览器环境:
- 如果使用WSL运行Next.js:
localhost指向WSL内部,而非宿主机的Django服务,需将请求地址改为宿主机IP(如http://192.168.x.x:8001/board/),或使用http://host.docker.internal:8001/board/(Windows)、http://172.17.0.1:8001/board/(Linux WSL)。 - 如果使用Docker容器运行Next.js:同样使用宿主机IP或
host.docker.internal(Mac/Windows)访问Django服务。
3. 优化Fetch请求配置
GET请求不需要设置Content-Type头(GET无请求体),冗余的头可能导致服务端解析异常,修改后的代码:
const data = await fetch(`http://localhost:8001/board/`, { method: 'GET', headers: { 'Accept': 'application/json', }, redirect: 'follow', cache: 'force-cache' });
4. 添加错误捕获获取详细信息
在fetch逻辑外包裹try-catch,打印更具体的错误信息,辅助排查:
try { const data = await fetch(`http://localhost:8001/board/`, { method: 'GET', headers: { 'Accept': 'application/json', }, redirect: 'follow', cache: 'force-cache' }); console.log('响应状态码:', data.status); console.log('响应内容:', await data.json()); } catch (error) { console.error('请求错误详情:', error); console.error('错误根源:', error.cause); }
5. 验证Django的CORS配置(可选)
虽然已设置CORS_ORIGIN_ALLOW_ALL = True,但可确认Django的CORS中间件是否正确添加到settings.py的MIDDLEWARE中:
MIDDLEWARE = [ # ...其他中间件 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # ...其他中间件 ]
内容的提问来源于stack exchange,提问作者user16700468
相关产品推荐
相关产品推荐

