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

React调用Node.js接口遇JSON解析错误,Postman请求正常求解

问题分析与解决方案

核心问题

你的Node.js服务端代码存在异步时序错误:connection.close()被直接放在connection.execute()外部调用,而execute是异步操作,这会导致数据库连接在SQL查询完成并向客户端发送响应之前就被关闭,最终返回给React的是不完整或空的响应内容,触发JSON解析失败。

修复后的服务端代码

修改app.get('/api/getDropdownOptions')的逻辑,将connection.close()移至execute的回调函数内部,确保连接在响应发送完成后再关闭:

app.get('/api/getDropdownOptions', (req, res) => {
    oracledb.getConnection(dbConfig, (err, connection) => {
        if (err) {
            console.error(err.message);
            return res.status(500).json({ error: 'Failed to connect to database' });
        }
        console.log('Connected to Oracle Database');

        const sql = 'SELECT nume FROM JUDETE';
        connection.execute(sql, (err, result) => {
            // 封装关闭连接的逻辑,确保无论成功失败都执行
            const closeConnection = () => {
                connection.close((err) => {
                    if (err) console.error(err.message);
                    console.log('Disconnected from Oracle Database');
                });
            };

            if (err) {
                console.error(err.message);
                res.status(500).json({ error: 'Failed to fetch dropdown options' });
                closeConnection();
                return;
            }

            console.log(result.rows);
            const dropdownOptions = result.rows.map((row) => ({ nume: row[0] }));
            console.log(dropdownOptions);
            
            res.json(dropdownOptions); // 用res.json自动设置Content-Type,无需手动配置
            closeConnection();
        });
    });
});

额外优化建议

  1. 用async/await简化异步逻辑:回调嵌套易出错,改用async/await让代码更直观:
app.get('/api/getDropdownOptions', async (req, res) => {
    let connection;
    try {
        connection = await oracledb.getConnection(dbConfig);
        console.log('Connected to Oracle Database');
        const sql = 'SELECT nume FROM JUDETE';
        const result = await connection.execute(sql);
        const dropdownOptions = result.rows.map((row) => ({ nume: row[0] }));
        res.json(dropdownOptions);
    } catch (err) {
        console.error(err.message);
        res.status(500).json({ error: 'Failed to fetch dropdown options' });
    } finally {
        if (connection) {
            try {
                await connection.close();
                console.log('Disconnected from Oracle Database');
            } catch (err) {
                console.error(err.message);
            }
        }
    }
});
  1. React端增加响应状态校验:在解析JSON前先确认响应是否成功,避免无效解析:
const fetchDropdownOptions = async () => {
    try {
        const response = await fetch('/api/getDropdownOptions');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json(); 
        setDropdownOptions(data);
    } catch (error) {
        console.error('Error fetching dropdown options:', error);
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 07:15:10