【问题标题】:When my nodejs app is tring to connect with SQL Server, nothing is showing on console, even if there is no error当我的 nodejs 应用程序尝试与 SQL Server 连接时,即使没有错误,控制台上也没有显示任何内容
【发布时间】:2021-11-08 11:29:11
【问题描述】:

以下代码属于index.js文件。

当我根据代码转到链接“localhost:300/admins/”时,它应该连接 SQL Server 并在控制台上返回结果。

我的 Microsoft SQL Server Management Studio 2012 运行良好,在 Visual Studio 中也可以顺利运行。

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const path = require('path');
const hbs = require('hbs');
const sql = require('mssql');
const sqlConfig = {
  user: 'xxx',
  password: 'xxxx',
  database: 'xxxxx',
  server: '127.0.0.1',
  port: xxxx,
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000,
  },
};

// static file's path set up
app.use(express.static('public'));
app.use('/css', express.static(__dirname + '/public'));
app.use('/images', express.static(__dirname + '/public'));
app.use('/js', express.static(__dirname + '/public'));

const pagespath = path.join(__dirname, './templates/views');
const partialspath = path.join(__dirname, './templates/partials');

// Set Views and view engine

app.set('view engine', 'hbs');
app.set('views', pagespath);
hbs.registerPartials(partialspath);

app.get('/', (req, res) => {
  res.render('home', { title: 'Home' });
});
app.get('/admins', function (req, res) {
  var result;
  async () => {
    try {
      const pool = await sql.ConnectionPool(config);
      const result = await pool.query`select name from tbl_info_p_admin`;
      res._write(result);
      console.log(result);
    } catch (err) {
      console.log(err);
    }
    await sql.close();
  };
  res.render('./admin/masters', { title: 'ADMIN' });
});

app.listen(process.env.PORT || 3000, function (err) {
  if (err) {
    console.log(err);
  } else {
    console.log('Server Started At Port 3000');
  }
});

【问题讨论】:

  • const pool = await sql.ConnectionPool(config); 将连接到什么?配置存储在sqlConfig 变量中。
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: node.js sql-server express sql-server-2012 hbs


【解决方案1】:

我可以看到您的代码中至少有两个问题

  1. 正如@AlwaysLearning 已经提到的,您的sql 配置对象定义为sqlConfig,但您使用sql.ConnectionPool(config)
  2. 当调用/admins 端点时,您的代码基本上什么都不做(res.render("./admin/masters", { title: "ADMIN"}); 除外,您正在使用async ()=>{...} 定义一个从未实际执行的匿名函数。要执行匿名函数,您可以使用 IIFE .在这种情况下,这不是一个好主意,因为会出现有关异步调用的问题。我怀疑你这样做是为了使用 async/await。要实现这一点,你不会将相关代码包装在匿名异步函数中,而是让整个回调函数异步。

const express = require('express');
const app = express();
const bodyParser = require("body-parser");
const path = require('path');
const hbs = require('hbs');
const sql = require('mssql')
const sqlConfig = {
  user: "xxx",
  password:"xxxx",
  database: "xxxxx",
  server: '127.0.0.1',
  port:xxxx,
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  }
}

// static file's path set up
app.use(express.static('public'));
app.use('/css', express.static(__dirname + '/public'));
app.use('/images', express.static(__dirname + '/public'));
app.use('/js', express.static(__dirname + '/public'));

const pagespath = path.join(__dirname, './templates/views');
const partialspath = path.join(__dirname, './templates/partials');

// Set Views and view engine

app.set('view engine', 'hbs');
app.set('views', pagespath);
hbs.registerPartials(partialspath);

app.get("/", (req, res) => {
  res.render("home", { title: "Home" });
});

app.get('/admins', async function(req, res) {
  try {
    const pool = await sql.ConnectionPool(sqlConfig);
    const result = await pool.query`select name from tbl_info_p_admin`;
    res._write(result);
    console.log(result)
  } catch (err) {
    console.log(err);
  }
  await sql.close();
  res.render("./admin/masters", { title: "ADMIN"}); 
});

app.listen(process.env.PORT || 3000, function (err) {
  if (err) {
    console.log(err);
  } else {
    console.log("Server Started At Port 3000");
  }
});

我自己无法对此进行测试,但希望对您有所帮助。

小幅补充:

  • 您可能想在 finally 子句中关闭 sql 连接
  • 最好不要在每次请求后关闭连接。但我不确定,因为我对 mssql 不太熟悉。

【讨论】:

    【解决方案2】:
    1. MSSQL 服务器连接配置。

      const config = {
        user: 'XX', // sql user
        password: 'xxxxxx', //sql user password
        server: '127.0.0.1', // if it does not work try- localhost
        database: 'xxxxxx',
        options: {
          trustServerCertificate: true,
          useColumnNames: true,        
          rowCollectionOnDone: true,
          trustedconnection: true,
          enableArithAbort: false,
          instancename: 'MSSQLSERVER',  // SQL Server instance name
          cryptoCredentialsDetails: {
             minVersion: 'TLSv1'
          },
        },
        port: 1433
      }
      module.exports = config;
      

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 2016-06-28
    • 2017-04-15
    • 2020-12-19
    • 2012-03-23
    相关资源
    最近更新 更多