You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Deno的Oak开发API时遇TypeError:request.body不是函数

问题分析与解决方案

核心错误原因

你遇到的TypeError - request.body is not a function是因为用GET请求处理需要接收请求体的添加操作:

  • Oak框架中,GET请求的request对象不存在body()方法,仅POST/PUT等带请求体的HTTP方法才会提供该方法。
  • 你的路由配置router.get('/api/v1/products', addProduct)违反REST规范——添加资源必须用POST请求。

分步修复

1. 修正路由方法

将route.ts中的路由改为POST:

router.post('/api/v1/products', addProduct)

2. 调整请求处理逻辑顺序

先判断是否存在请求体,再执行解析操作,同时替换宽泛的any类型为Oak官方类型:

import type { Request, Response } from "https://deno.land/x/oak/mod.ts";

const addProduct = async(
    { request, response } : { request: Request, response: Response },
) => {
    if (!request.hasBody) {
        response.status = 400;
        response.body = {
            success: false,
            msg: "No data",
        };
        return; // 提前终止,避免后续无效执行
    }

    const body = await request.body();
    const product: Product = body.value;
    products.push(product);
    response.status = 201;
    response.body = {
        success: true,
        data: product,
    };
};

3. 修复server.ts的模板字符串错误

原代码用单引号包裹模板字符串,导致${port}无法解析,改为反引号:

const port = 5000;
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
console.log(`Server running on port ${port}`);
await app.listen({ port });

4. Postman测试规范

  • 请求方法选择POST
  • 请求体选择raw -> JSON格式,输入产品JSON数据
  • 确保请求头Content-Type设置为application/json

额外优化建议

  • 始终使用Oak提供的Request/Response类型替代any,获得类型提示以避免低级错误
  • 可添加请求体校验逻辑,确保传入数据符合Product结构要求

内容的提问来源于stack exchange,提问作者Solène Elina Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 00:05:00