连接关闭错误在Azure上调用Node.js API

时间:2019-10-09 18:38:49

标签: node.js sql-server azure

我有一个调用我的本地SQL Server的nodejs Rest API。它托管在Azure上,并使用Azure Hybrid Connection连接到我的SQL Server。所有操作均在本地计算机上按预期运行,但是在Azure上,当我尝试调用以下“测试”路由时,出现ConnectionClosed错误(ECONNCLOSED):

这是我的代码示例:

d_list <- lapply(split(d,d$study.name), 
                 #Find columns with similar values using sapply and length(unique(cols)) 
                 #then get the 1st row
                 function(x) x[1, sapply(x,function(y) length(unique(y))==1)])
do.call('rbind.data.frame',d_list)

           study.name ESL prof ESL.1 prof.1
Bit.KnoA     Bit.KnoA   1    3     1      3
Bit.KnoB     Bit.KnoB   1    2     1      2
ChandlerA   ChandlerA   1    2     1      2
Mubarak       Mubarak   2   NA     2     NA
SheenA         SheenA   1    2     1      2
Shin.Ellis Shin.Ellis   1    2     1      2
Sun               Sun   2    2     2      2
Trus.Hsu     Trus.Hsu   2    2     2      2

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

这是我可行的示例:

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

var sqlConfig = {
    user: 'jack', 
    password: 'password',
    database: 'jackdemo',
    server: 'jackdemo.database.windows.net',
    options: {
        encrypt: true
    }
}

var server = app.listen(process.env.PORT || 8081, function () {
    var host = server.address().address
    var port = server.address().port

    console.log("app listening at http://%s:%s", host, port)
});

app.get('/', function(req, res) {
    res.json({"message": "Welcome to the API"});
});

app.get('/Test', function (req, res) {
    sql.connect(sqlConfig, function() {
        var request = new sql.Request();
        request.query("select 1 as number") 
        .then(result => {
          let rows = result.recordset //first recordset
          res.setHeader('Access-Control-Allow-Origin', '*')
          res.status(200).json(rows);
          sql.close();
        }).catch(err => {
          console.log(err);
          res.status(500).send({
            message: err
          })
          sql.close();
        });
    })
});

您也可以使用官方教程中的方法:Use Node.js to query an Azure SQL database


顺便说一句,请确保已为Azure SQL正确配置了防火墙规则。您需要将客户端IP添加为允许的列表,例如:https://docs.microsoft.com/en-us/azure/sql-database/sql-database-firewall-configure#create-and-manage-ip-firewall-rules

答案 1 :(得分:0)

好,我通过从sqlConfig中删除驱动程序和实例名称来解决此问题:

var sqlConfig = {
    user: 'restapi', //remove if using Windows Auth
    password: 'restapi', //remove if using Windows Auth
    database: 'dbname',
    server: 'server',
    options: {
        encrypt: true
    }
}