Соединение с rest-API и SQL-сервером или Azure - PullRequest
0 голосов
/ 01 декабря 2019

У меня проблема с подключением к моей базе данных, расположенной в Azure, я пытался установить соединение с создаваемым мной API-интерфейсом отдыха, с базой данных в Azure, которой я управляю напрямую из SQL Server. , и я не могу установить соединение с этим.

Я пытаюсь соединиться с другой тестовой базой данных в SQL Server.

API остальных rest ia create находится в NodeJS

var sql = require('mssql');
var dbconfig = {
    server:"Fernando\EQUIPO",
    user: "<user>",
    password: "<password>",
    database: "<dbname>",
    port: 1433,
    option: {
        encrypt: false
    }
};

function getList() {
    var record;
    var conn = new sql.ConnectionPool(dbconfig);
    conn.connect(function(err){
        if(err) throw err;
        var req = new sql.Request(conn);
        req.query("select * from cliente", function(err, recordset) {
            if(err) throw err;
            else {
                console.log(recordset);
                record = recordset;
            }
            conn.close();
        });
    });
    return record;
}

const { Router } = require('express');
const router = Router();

const _ = require('underscore');

const movies = require('../sample.json');

router.get('/', (req, res) => {
    res.send(getList());
});

Когда я делаю «get» для моего локального хоста http://localhost:3000/api/movies, в консоли появляется следующее сообщение:

GET /api/movies 200 126.188 ms - -
(node:11868) UnhandledPromiseRejectionWarning: ConnectionError: Failed to connect to FernandoEQUIPO:1433 - getaddrinfo ENOTFOUND FernandoEQUIPO
    at Connection.tedious.once.err (C:\Users\luisn\Desktop\rest-API\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
    at Object.onceWrapper (events.js:286:20)
    at Connection.emit (events.js:198:13)
    at Connection.socketError (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connection.js:1258:12)
    at _connector.Connector.execute (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connection.js:1084:21)
    at GetAddrInfoReqWrap._dns.default.lookup [as callback] (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connector.js:152:16)        
    at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:68:17)
(node:11868) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:11868) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Ответы [ 2 ]

0 голосов
/ 02 декабря 2019

Подключение к базе данных SQL Azure:

Вот пример кода подключения к базе данных SQL Azure с помощью REST-API: enter image description here

Примечание: encrypt должно быть true.

Имя сервера можно получить на портале: enter image description here

И вам нужно добавить IP-адрес клиента в настройки брандмауэра SQL Server Azure : enter image description here

Затем вы можете подключиться к AzureБаза данных SQL сейчас. Вы можете сослаться на: Создание REST API Node.js в Azure

Подключение к SQL Server:

Ваш код почти правильный и требует некоторого количестваизменить:

var sql = require('mssql');
var dbconfig = {
    server:"localhost",
    user: "<user>",
    password: "<password>",
    database: "<dbname>",
    port: 1433,
    option: {
        encrypt: false
    }
};

Как сказал Абхишек Ранджан, вы должны ввести ip вашего сервера.

Надеюсь, это поможет.

0 голосов
/ 01 декабря 2019

Добро пожаловать в StackOverflow.

ConnectionError: Failed to connect to FernandoEQUIPO:1433 - getaddrinfo ENOTFOUND FernandoEQUIPO

В вашей ошибке указано, что невозможно установить соединение, так как не удалось найти сервер по указанному адресу. Убедитесь, что сервер запущен, и проверьте подключение с помощью какого-либо стороннего приложения.
Вы уверены, что FernandoEQUIPO разрешено на правильное имя хоста?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...