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

Node.js项目使用Knexjs执行SQL Server迁移时出现认证错误求助

KnexJS连接SQL Server迁移时出现认证错误排查

已解决: 解决方案请参阅评论区我的评论。

我刚学习KnexJS(数据库新手),用于连接Microsoft SQL Server与Node.js后端,跟着教程搭建了如下项目结构:

|- knexjs (主文件夹)
   |- db
      |- migrations
         |- 20230307141431_init.js
      |- db.js
      |- knexfile.js
   |- node_modules
   |- index.js
   |- package-lock.json
   |- package.json

但执行迁移将20230307141431_init.js的改动同步到已创建的knexjs_database数据库时,出现认证错误。我已反复核对密码,确认密码正确。

执行的迁移命令:

npx knex migrate:latest --knexfile ./db/knexfile.js

错误截图:
Knexjs迁移错误

我新建了admin用户,并将其添加到knexjs_database的安全组中:
SSMS SQL Server用户配置


项目文件内容

index.js

const express = require("express");

const app = express();
app.use(express.json());

app.get("/", (req, res) => {
  res.end("Hello World!");
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

knexfile.js

module.exports = {
  development: {
    client: "mssql",
    connection: {
      host: "127.0.0.1",
      port: 1433,
      database: "knexjs_database",
      user: "admin",
      password: "*********",
      options: {
        trustedConnection: true,
      },
    },
    pool: {
      min: 2,
      max: 10,
    },
    migrations: {
      tableName: "knex_migrations",
    },
  },
};

db.js

const knex = require("knex");
const knexfile = require("./knexfile");

const db = knex(knexfile.development);
module.exports = db;

20230307141431_init.js

exports.up = function (knex) {
  return knex.schema.createTable("person", (table) => {
    table.increments("id").primary();
    table.string("email").notNullable().unique();
    table.string("first_name").notNullable();
    table.string("last_name").notNullable();
    table.timestamps(true, true);
  });
};

exports.down = function (knex) {
  return knex.schema.dropTable("person");
};

package.json

{
  "name": "knexjs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "knex": "^2.4.2",
    "mssql": "^9.1.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

排查方向

  • 禁用Windows身份验证
    你的knexfile.js中设置了trustedConnection: true,这会强制使用Windows身份验证,忽略配置的账号密码。将该选项改为false或直接删除,再重新执行迁移命令。

  • 检查SQL Server身份验证模式
    确保SQL Server实例开启了混合身份验证模式(SQL Server和Windows身份验证模式)。若仅开启Windows身份验证,SQL Server不会接受账号密码登录。

  • 验证用户权限
    确认admin用户不仅加入数据库安全组,还拥有knexjs_database的读写及建表权限。可在SSMS中给用户分配db_owner角色测试。

  • 检查服务与端口
    确保SQL Server服务(MSSQLSERVER)正在运行,且1433端口处于监听状态。可通过命令netstat -ano | findstr :1433验证端口占用情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 08:52:57