Проверьте, активен ли сервер MySQL NodeJS или нет

Опубликовано: 26 Июля, 2021

Мы увидим, как проверить, активен ли сервер, на котором размещена наша база данных MySQL.

Синтаксис:

 database_connection.ping (обратный вызов);

Модули:

  • NodeJS
  • ExpressJS
  • MySQL

    Настройка среды и выполнения:

  1. Создать проект

     npm init 

  2. Установить модули

     npm установить экспресс
    npm установить mysql 

    Файловая структура:

  3. Создать сервер

    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 ...`);
    });
  4. Создание и экспорт объекта подключения к базе данных

    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;
  5. Создайте маршрут для проверки активности сервера 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" );
    })
    });
  6. Запустить сервер

     узел index.js
  7. Вывод: поместите эту ссылку в свой браузер http: // localhost: 5000 / getMysqlStatus

    • Если сервер не активен, вы увидите в своем браузере следующий вывод:
     Сервер MySQL не работает 

    • Если сервер активен, вы увидите в своем браузере следующий вывод:
     Сервер MySQL активен