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

Node.js连接SQL Server报错:TypeError: Cannot read 'request' of undefined

解决TypeError: Cannot read properties of undefined (reading 'request')问题

错误信息

return pool.request().query('SELECT * FROM Products', function (err, result) {
                      ^

TypeError: Cannot read properties of undefined (reading 'request')

问题根源

  1. 连接失败时无返回值:你的getConnection函数在数据库连接出错时,仅打印错误但未返回任何值,导致调用await getConnection()得到undefined,后续调用pool.request()必然报错。
  2. 模块导入导出不匹配:connection.js混用了CommonJS的require和ES模块的export,如果项目未正确配置ES模块支持,会导致导入失败,pool同样为undefined。

修复方案

1. 修复连接函数的错误处理

修改connection.js,确保连接失败时抛出错误,让上层控制器处理:

const sql = require('mssql/msnodesqlv8');

const dbSettings = {
    user: '******',
    password: '******',
    server: "DESKTOP-*****\\SQLEXPRESS",
    database: 'webstore',
    driver: 'msnodesqlv8',
    options: {
        encrypt: true,  // for azure
    }
}

export async function getConnection() {
    try {
        const pool = await sql.connect(dbSettings); 
        return pool;
    } catch (error) {
        console.error('数据库连接失败:', error);
        // 抛出错误,避免返回undefined
        throw error;
    }
}

2. 给控制器添加错误捕获

修改products.controller.js,捕获异常并返回合理响应:

import {getConnection} from '../database/connection';

export const getProducts = async (req, res) => {
    try {
        const pool = await getConnection();
        const result = await pool.request().query('SELECT * FROM Products');
        
        console.log(result);
        res.json(result.recordset); // 返回实际查询结果,而非固定字符串
    } catch (error) {
        console.error('获取产品数据失败:', error);
        res.status(500).json({ message: '加载产品数据失败,请稍后重试' });
    }
};

3. 统一模块系统

如果你的项目使用CommonJS(即package.json中没有"type": "module"),需要统一导入导出方式:

  • 修改connection.js的导出:
async function getConnection() {
    // ... 原有代码 ...
}

module.exports = { getConnection };
  • 修改products.controller.js的导入:
const { getConnection } = require('../database/connection');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:50:27