A Node.js server is a backend system built using Node.js, a runtime environment that allows you to write server-side applications in JavaScript. This server can handle incoming requests, process data, communicate with databases, and return responses to the client (such as a web browser or mobile app). Here’s a breakdown of how a Node server works and why it’s popular:
In short, a Node.js server provides a fast, efficient way to handle web requests, especially for applications that require real-time interactions and high scalability.
/* *******************************************************************************************
* Author: V. Demir, 30.10.2024
* *******************************************************************************************
* Description:
* Express-Server, that takes a request from the browser, fetches the result from the
* database, and provides the browser with the requested data.
* *******************************************************************************************
* Hints:
* Before programming the server the following list of JS-Modules
* must be imported to our IDE. Execute the commands below in the terminal!
* npm install node
* npm init -y
* npm install mysql
* npm install body-parser
* npm install express
** ***************************************************************************************** */
// Reference: www.npmjs.com/package/mysql
const mysql = require("mysql"); // import of the mysql-package
const express = require('express'); // import of the express-package/middleware
const port = 3000; // ThKind of a telefon number, on which the server listens for requests
// Variable set with the db-connection credentials to connect the server to the database
const config = {
host: 'localhost',
database: 'myDatabase',
user: "restrictedUser",
password: 'SafePassword123'
}
const connection = mysql.createConnection(config)
// connection line to the database, that takes the credentials
// and returns a open line to execute sql statements
// function that actually connects the server to the database
// result is successful or errormessage
connection.connect(function(err) {
if (err) throw err;
console.log('Connected to MySQL database:', connection.config.database);
// Preparation of the sql statement, which will be send to the database
var sqlstmt = 'SELECT sysdate()';
connection.query(sqlstmt, function (err, result) {
// the sqlstmt is send to the database
if (err) throw err; // if everthing is fine, i receive the resultset
console.table(result); // We can present the result as a table
console.log(result); // Or as a unformated string
});
});