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

TypeORM初始化mssql数据源报错:config.server必填且需为字符串

解决TypeORM连接MSSQL时的"The 'config.server' property is required..."错误

问题场景

在TypeScript环境中使用TypeORM初始化MSSQL类型的DataSource时,触发错误提示:

'The "config.server" property is required and must be of type string'

当前使用的DataSource初始化代码:

import path from 'path'
import { DataSource } from 'typeorm'

const dataSource = new DataSource({
    type: 'mssql',
    host: process.env.SERVER,
    username: process.env.USERNAME,
    password: process.env.PASSWORD,
    database: process.env.DATABASE,
    entities: [path.join(__dirname, '/../**/*.entity.{js,ts}')],
    entityPrefix: '',
    logging: true,
    options: {
        encrypt: false,
        //instanceName: 
    },
    pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000,
    }
})

该错误来自tedious库的tedious/src/connection.ts校验逻辑:

constructor(config: ConnectionConfiguration) {
    super();

    if (typeof config !== 'object' || config === null) {
      throw new TypeError('The "config" argument is required and must be of type Object.');
    }
    if (typeof config.server !== 'string') {
      throw new TypeError('The "config.server" property is required and must be of type string.');
    }

    this.fedAuthRequired = false
}

解决方法

1. 确保环境变量正确加载

错误根源是process.env.SERVER未读取到有效值,导致传递给tedious的server参数为undefined:

  • 确认项目中存在.env文件,且文件内包含SERVER字段(值为MSSQL服务器地址);
  • 在代码开头添加环境变量加载逻辑(需先安装dotenv:npm install dotenv --save-dev):
    import 'dotenv/config'
    

2. 改用server字段替代host

TypeORM针对MSSQL的配置中,host和server均可指定服务器地址,但tedious库明确要求server参数,直接使用server字段可避免映射问题:
将配置中的host: process.env.SERVER修改为server: process.env.SERVER。

3. 显式校验环境变量类型

确保环境变量值为有效字符串,避免因变量为空或类型错误触发校验失败:

// 提前校验并获取环境变量
const server = process.env.SERVER as string;
if (!server) {
  throw new Error('环境变量SERVER未配置或值为空');
}

修改后的完整代码示例

import path from 'path'
import 'dotenv/config'
import { DataSource } from 'typeorm'

// 校验环境变量完整性
const server = process.env.SERVER as string;
const username = process.env.USERNAME as string;
const password = process.env.PASSWORD as string;
const database = process.env.DATABASE as string;

if (!server || !username || !password || !database) {
  throw new Error('数据库连接所需的环境变量未完全配置');
}

const dataSource = new DataSource({
    type: 'mssql',
    server: server,
    username: username,
    password: password,
    database: database,
    entities: [path.join(__dirname, '/../**/*.entity.{js,ts}')],
    entityPrefix: '',
    logging: true,
    options: {
        encrypt: false,
        //instanceName: 
    },
    pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000,
    }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 05:13:20