Проверьте, активен ли сервер MySQL NodeJS или нет
Опубликовано: 26 Июля, 2021
Мы увидим, как проверить, активен ли сервер, на котором размещена наша база данных MySQL.
Синтаксис:
database_connection.ping (обратный вызов);
Модули:
- NodeJS
- ExpressJS
- MySQL
Создать проект
npm init
Установить модули
npm установить экспресс npm установить mysql
Файловая структура:
Создать сервер
index.js
const express = require(
"express"
);
const database = require(
'./sqlConnection'
);
const app = express();
app.listen(5000, () => {
console.log(`Server is up and running on 5000 ...`);
});
Создание и экспорт объекта подключения к базе данных
sqlConnection.js
const mysql = require(
"mysql"
);
let db_con = mysql.createConnection({
host:
"localhost"
,
user:
"root"
,
password:
''
});
db_con.connect((err) => {
if
(err) {
console.log(
"Database Connection Failed !!!"
, err);
}
else
{
console.log(
"connected to Database"
);
}
});
module.exports = db_con;
Создайте маршрут для проверки активности сервера mysql.
app.get(
"/getMysqlStatus"
, (req, res) => {
database.ping((err) => {
if
(err)
return
res.status(500).send(
"MySQL Server is Down"
);
res.send(
"MySQL Server is Active"
);
})
});
Полный файл index.js:
Javascript
const express = require(
"express"
);
const database = require(
'./sqlConnection'
);
const app = express();
app.listen(5000, () => {
console.log(`Server is up and running on 5000 ...`);
});
app.get(
"/getMysqlStatus"
, (req, res) => {
database.ping((err) => {
if
(err)
return
res.status(500).send(
"MySQL Server is Down"
);
res.send(
"MySQL Server is Active"
);
})
});
Запустить сервер
узел index.js
Вывод: поместите эту ссылку в свой браузер http: // localhost: 5000 / getMysqlStatus
- Если сервер не активен, вы увидите в своем браузере следующий вывод:
Сервер MySQL не работает
- Если сервер активен, вы увидите в своем браузере следующий вывод:
Сервер MySQL активен
Настройка среды и выполнения: