Deno Fresh框架无法连接Oak后端服务器,如何解决?
问题描述
我有一个由Oak(Deno版Express)服务器和Fresh服务器组成的项目,两者单独启动后均可正常运行,但Fresh无法连接到Oak后端。Postman测试Oak的/users接口可正常返回所有用户数据。
Fresh应用的routes目录结构如下:
routes ├── about.tsx ├── index.tsx ├── users │ ├── [id].ts │ └── [id].tsx ├── sampledata.ts └── sampledata.tsx
相关文件代码:
sampledata.tsx
/** @jsx h */ import { h } from "preact"; import { PageProps } from "$fresh/server.ts"; import Layout from '../components/layouts.tsx'; export default function SampleData({props}:PageProps) { console.log(props); return ( <Layout> <ul> {props.data.map(post => { return <li>{post.email}</li> })} </ul> </Layout> ) }
sampledata.ts
import { Handlers } from "$fresh/server.ts" export const handler: Handlers = { async GET(_req, ctx) { const rawPosts = await fetch('http://localhost:4000/users'); const posts = await rawPosts.json(); console.log(posts); return ctx.render(posts); } }
访问http://localhost:8000/sampledata时出现错误,需要排查失败原因并实现Fresh到Oak的正确API调用。
失败原因分析
核心错误是Fresh的ctx.render()参数格式不正确:
- Fresh的
ctx.render()需要接收一个包含data属性的对象,该对象的data值会被传递给页面组件的props.data。 - 当前代码直接将
posts数组传入ctx.render(posts),导致页面组件的props直接等于这个数组,props.data变为undefined,执行props.data.map()时就会抛出Cannot read properties of undefined (reading 'map')的错误。
其他次要排查点(修复后仍有问题时检查):
- 确认Oak服务器确实监听在
localhost:4000,未绑定到特定IP(比如仅绑定127.0.0.1但Fresh运行在容器环境)。 - 检查Deno网络权限:Fresh启动时是否添加了
--allow-net参数(默认Deno会限制网络请求)。
修复方案
- 修正sampledata.ts中的handler代码,将
posts包装到data属性中传入ctx.render(),同时增加错误处理:
import { Handlers } from "$fresh/server.ts" export const handler: Handlers = { async GET(_req, ctx) { try { const rawPosts = await fetch('http://localhost:4000/users'); // 检查响应状态,确保请求成功 if (!rawPosts.ok) { throw new Error(`HTTP error! status: ${rawPosts.status}`); } const posts = await rawPosts.json(); console.log(posts); // 正确传递数据:将posts放到data属性中 return ctx.render({ data: posts }); } catch (err) { console.error("Failed to fetch data:", err); // 返回错误页面或状态码 return new Response("Failed to load data", { status: 500 }); } } }
- 确保Fresh启动时拥有网络权限:启动Fresh时添加
--allow-net参数,示例命令:
deno task start --allow-net
- 验证页面组件逻辑:当前
sampledata.tsx的逻辑是正确的,props.data会接收到handler传递的用户数组,可正常执行map渲染。
内容的提问来源于stack exchange,提问作者ChristianOConnor
相关产品推荐
相关产品推荐

