NodeJS Express HTTP请求暂停2分钟

时间:2018-06-20 19:56:59

标签: node.js http express https

我有一个运行express的nodeJS服务器,并且正在进行API调用以从角度应用程序访问服务器上的数据库。

当我向本地主机服务器发出2次http调用时,总是会停顿2分钟。从chrome开发工具的图片中可以看出。

我一直在研究它,发现chrome一次不能拥有6个以上的TCP连接。我是否正确连接到数据库,如何防止2分钟的停顿?

enter image description here

Server.js

var express = require('express');
var app = express();
const sql = require('mssql');
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));

var dbConfig = {
    server: 'DATABASESERVER',
    database:'DB1',
    user:'ADMIN',
    password:'WHATEVERPASS',
    port:1600
};

var colorDBConfig = {
  server:'DATABASESERVER',
  database:'DB2',
  user:'ADMIN',
  password:'WHATEVERPASS',
  port:1700
};

var usersDBConfig = {
  server:'DATABASESERVER',
  database:'DB3',
  user:'ADMIN',
  password:'WHATEVERPASS',
  port:1800
};


app.get('/carlist',function(req,res){
  console.log("I have recieved car request");
    sql.close()
    sql.connect(dbConfig).then(pool => {
        return pool.request()
        .execute('dbo.getCarsJoinColor')
    }).then(result => {
        var carlist = result.recordsets[0];
        res.json(carlist);
        sql.close()
    }).catch(err => {
        console.log("Oopsy Woopsy that's not right!");
        console.log(err);
        sql.close();
        return err;
    })
});

app.get('/carcolorlist',function(req,res){
    console.log("modal request recieved");
    sql.close()
    sql.connect(colorDBConfig).then(pool => {
        return pool.request()
        .execute('dbo.getColorCarsJoinCars')
    }).then(result => {
        var carColorList = result.recordset;
        res.json(carColorList);
        sql.close()
   }).catch(err => {
        console.log("Oopsy Woopsy that's not right!");
        console.log(err);
        sql.close();
      return err;
   })
});

app.post('/login', function(req, res) {
  sql.close()
  sql.connect(usersDBConfig).then(pool => {
    return pool.request()
    .query('SELECT * FROM Users.dbo.Accounts WHERE Name = ' + "'" + req.body.QNumber + "'" + 'AND Password = ' + "'" + req.body.Password + "'")
  }).then(result => {
    var user = result.recordset;
    res.json(user);
    sql.close()
  }).catch(err => {
    console.log("Oopsy Woopsy that's not right!");
    console.log(err);
    sql.close();
    return err;
  })
})

1 个答案:

答案 0 :(得分:0)

必须建立全局连接,然后将这些全局连接用于每个路由。

var dbConn = new sql.ConnectionPool(dbConfig);
var dbColorConn = new sql.ConnectionPool(colorDBConfig);
var dbUserConn = new sql.ConnectionPool(usersDBConfig);

//Within the route
var request = new sql.Request(dbConn);
request.execute('dbo.getUsers').then(function (result) {
res.json(result.recordsets[0]);
dbConn.close();