连接到 SQL Server(使用“mssql”)?"/>
在 Azure App Service 上托管时如何将 Node.js 服务器应用程序连接到 SQL Server(使用“mssql”)?
几个月来,我一直致力于 Node.js Express 应用程序,它成功连接到 SQL Server (2016) 并顺利运行查询。
在配置到数据库的连接、在 apache2 上部署和托管以及向 Node.js 服务器发送请求并通过 SQL Server 查询检索数据的 React 客户端应用程序后,我准备好应用程序。
需要使用 Azure 托管应用程序,我遵循了 ;pivots=development-environment- 上的文档vscode,要部署我的 Node.js 服务器应用程序并跳过“创建您的 Node.js 应用程序”,部署成功并且使用 Postman 我从 Azure 给我的域(从不查询数据库的路由)中得到了正确的响应。
但是我在日志流中遇到错误:
ConnectionError:无法在 15000 毫秒内连接到 XX.XXX.XX.XX:XXXX。
如果我在本地工作或使用 Apache 域,则连接建立没有错误。
我需要对 Node.js 应用程序/Azure/SQL Server 进行哪些调整才能修复它?
这是我的 Node.js 应用程序:
mssql.js
我得到它:
var sql = require("mssql");
require("dotenv").config();
const config = {
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
server: process.env.DB_SERVER,
port: JSON.parse(process.env.DB_PORT),
database: process.env.DB_NAME,
requestTimeout: 3600000, //an hour
options: {
trustedConnection: true,
trustServerCertificate: true,
encrypt: true,
},
debug: true,
parseJSON: true,
};
let pool;
const initConnect = async () => {
try {
const pool = await sql.connect(config);
return pool;
} catch (err) {
console.log(err.message);
console.log("Error connecting to DB...", err);
sql.close();
}
};
const initMod = async () => {
this.pool = await initConnect();
console.log("open connecion...");
};
initMod();
module.exports.pool = pool;
module.exports.SQLInst = sql;
这是 server.js 文件: (我也在日志中看到当请求 /getItems 时 sql.pool 是未定义的)
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const sql = require("./mssql");
const port = process.env.PORT || 3000;
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get("/", async (req, res) => {
res.send("Welcome to test server!");
});
// Getting items from db
app.get("/getItems", async (req, res) => {
console.log(`Getting items...`);
try {
const data = await sql.pool.request().query("SELECT * FROM PartsPics");
const items = await data.recordset;
res.status(200).send(items);
} catch (e) {
console.log("Error occured: ", e);
res.status(500).send(e);
}
});
我尝试了在配置对象上看到的几种解决方案,但没有修复错误。
我确保在 SQL Server 配置管理器中启动模式设置为自动并启用 TCP/IP。
回答如下:更多推荐
在 Azure App Service 上托管时如何将 Node.js 服务器应用程序连接到 SQL Server(使用“mssql”)?
发布评论