【问题标题】:Why does the script get stuck on the connection in this nodejs script为什么脚本会卡在这个nodejs脚本中的连接上
【发布时间】:2019-01-09 15:06:15
【问题描述】:

我正在使用来自http://www.tutorialsteacher.com/nodejs/access-sql-server-in-nodejs 的以下内容:

var express = require('express');
var app = express();

app.get('/', function (req, res) {

    var sql = require("mssql");

    // config for your database
    var config = {
        user: 'sa',
        password: 'mypassword',
        server: 'localhost', 
        database: 'SchoolDB' 
    };

    // connect to your database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records
        request.query('select * from Student', function (err, recordset) {

            if (err) console.log(err)

            // send records as a response
            res.send(recordset);

        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

当我在浏览器中运行这个文件时,页面第一次运行。但是如果我刷新它,它会说连接未打开。当我在 webserver 上下文之外运行它时,它永远不会退出 sql.connect 函数,并且需要在 Node.js 中使用 Control-C 停止。有谁知道为什么这段代码会卡在 sql.connect 函数中?

【问题讨论】:

    标签: sql-server node.js express


    【解决方案1】:

    首先:您使用的示例基于node-mssql 的2.3 版。当前版本现在是 4.1。使用node-mssql 的一种推荐方法是使用connectionPools。我调整了您的代码以使用池。

    第二:如果有错误,在你的代码中你永远不会到达res.send()。所以我修改了你的代码,以便在出现错误时发回一些东西。

    还有一个提示:我会将依赖项放在您的应用程序的顶部(而不是在路由内)...无论哪种方式都可以,但是您的代码会变得更加清晰。

    'use strict';
    
    const express = require('express');
    const app = express();
    const sql = require("mssql");
    
    // config for your database
    const config = {
        user: 'sa',
        password: 'mypassword',
        server: 'localhost', 
        database: 'SchoolDB',
        options: {
            encrypt: false
        },
        pool: {
            max: 10,
            min: 0,
            idleTimeoutMillis: 30000
        }    
    };
    
    // create a connection pool
    const pool = new sql.ConnectionPool(config, err => {
        if (err) {
            console.log(err);
        }
    });
    
    app.get('/', function (req, res) {
    
        // create Request object (using the connection pool)
        const request = new sql.Request(pool);
    
        // query to the database and get the records
        request.query('select * from Student', (err, recordset) => {
            if (err) {
                console.log(err);
                res.send(err);
            } else {
                // send records as a response
                res.send(recordset);
            }
        });
    });
    
    var server = app.listen(5000, function () {
        console.log('Server is running..');
    });
    

    希望有所帮助(上面的代码未经测试...)

    【讨论】:

      猜你喜欢
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 2015-03-11
      • 1970-01-01
      • 2020-12-14
      • 2016-12-27
      相关资源
      最近更新 更多