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

在Zoho Catalyst框架中使用Express无法获取req.body的问题

Zoho Catalyst中req.body无法获取的解决方案

问题原因

你在Catalyst云函数里错误初始化了独立的Express实例并添加解析中间件,但Catalyst会直接传入已封装的req/res对象,你创建的Express app并未处理当前请求,导致中间件完全不生效,req.body自然无法被解析。

修复步骤

  1. 移除冗余的Express初始化代码
    删除函数内的express引入、app创建及中间件注册代码,直接使用Catalyst传入的req对象。

  2. 确保请求Content-Type与数据格式匹配
    在Postman中发送请求时:

    • 发送JSON数据,需设置Content-Type: application/json
    • 发送表单数据,需设置Content-Type: application/x-www-form-urlencoded

修正后的代码示例

module.exports = (req, res1) => {
    const debug = require('debug');
    const https = require('https');
    const tools = require('./tools.js');
    const crypto = require('crypto');

    function getHash(){
        var hmac = crypto.createHmac('sha256', apisecretkey);
        hmac.update(dataToSign);
        return hmac.digest('base64');
    };

    var url = req.url;

    switch (url) {
        case '/scanName':
            // Catalyst默认会根据Content-Type解析请求体
            console.log(req.body);
            console.log(req.get('Accept'));
            console.log(req.accepts('application/json'));
            res1.write('xx');
            res1.end();
            break;
        case '/':
            // 补充根路径处理逻辑
            res1.end('Root endpoint');
            break;
        default:
            res1.status(404).end('Endpoint not found');
    }
};

手动解析兜底方案(若自动解析失效)

如果Catalyst默认解析未生效,可针对特定Content-Type手动解析请求体:

case '/scanName':
    if (req.headers['content-type']?.includes('application/json')) {
        let rawBody = '';
        req.on('data', chunk => rawBody += chunk.toString());
        req.on('end', () => {
            try {
                const parsedBody = JSON.parse(rawBody);
                console.log(parsedBody); // 此时可获取解析后的请求体
                res1.write('xx');
                res1.end();
            } catch (err) {
                console.error('JSON解析失败:', err);
                res1.status(400).end('Invalid JSON');
            }
        });
    } else {
        // 处理其他Content-Type的情况
        console.log(req.body);
        res1.write('xx');
        res1.end();
    }
    break;

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:35:29