如何将现有的Node.js服务器应用程序连接到Azure SQL数据库 [英] How to connect an existing nodejs server app to Azure SQL database

查看:46
本文介绍了如何将现有的Node.js服务器应用程序连接到Azure SQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以建议:

我有一个运行在azure上的现有nodejs服务器,在Linux上运行的节点10.14.项目代码在github上,当我推送更改时,它们会自动推送到天蓝色.

我已经通过Azure门户设置了数据库服务器和数据库,并且可以通过Azure门户进行查询.

我想修改nodejs服务器以连接到数据库,我有连接字符串代码等,但是只是添加以下行:

  var mysql = require('mysql'); 

将停止服务器窗体的运行,因为大概我没有在Azure云中运行服务器的计算机上安装mysql.

如何使它正常工作?

感谢您的帮助,米奇.

解决方案

根据该错误,您不会在 package.json 文件中添加软件包,也不会在项目中安装该软件包.此外,如果要连接Azure SQL服务器数据库,我们可以使用包

Can anyone please advise:

I have an existing nodejs server running on azure, running node 10.14 on Linux. The project code is on github and when I push changes they are automatically pushed to azure.

I have set up a database server and database though the Azure portal and can query it through the Azure portal.

I want to modify the nodejs server to conect to the database, I have the connection string code etc. but just the act of adding the line:

var mysql = require('mysql'); 

will stop the server form running as presumably I have not installed mysql on the machine which is running the server in the Azure cloud.

How can I get this to work?

Thanks for any help, Mitch.

解决方案

According to the error, you do not add the package in your package.json file and install the package in your project. Besides, if you want to connect Azure SQL server database, we can use package mssqql

For example

  1. My package.json file

{
....
  
    "dependencies": {
        "express": "^4.17.1",
        "mssql": "^6.2.0",
        "request": "^2.88.2"
    }

}

  1. code

const router = express.Router()
const sql = require('mssql')


const config = {

  user: "<user name>",
  password: "<password>",
  server: "<your SQL server name>.database.windows.net",
  port: 1433,
  database: "test",
  connectionTimeout: 3000,
  parseJSON: true,
  options: {
    encrypt: true,
    enableArithAbort: true
  },
  pool: {
    min: 0,
    idleTimeoutMillis: 3000
  }
};
const pool = new sql.ConnectionPool(config);
const poolConnect = pool.connect();

router.get('/', async function (req, res) {
  
  await poolConnect;
  try {
    const request = pool.request(); 
    const result = await request.query('select 1 as number')
    console.log(result);
    res.json(result.recordset);
    
} catch (err) {
    console.error('SQL error', err);
    res.send(err);
}
});

  1. Test.

这篇关于如何将现有的Node.js服务器应用程序连接到Azure SQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆