We're going to set up a small node server to host our own application. The first thing to do is create an app folder. After that lets configure our package.json
with the dependencies we will need for this. Since we only need express, there is only one dependency, "express": "^4.19.2"
{
"name": "server-app",
"version": "0.0.2",
"dependencies": {
"express": "^4.19.2",
"module": "^1.2.5"
}
}
Now from the commandline in the app folder we will run npm install
, which will install express for us. Once installed we can start with our basic server configuration using the code below.
app/server.js
const express = require('express');
const path = require('path');
const app = express();
const PORT = 43451;
const { spawn } = require('child_process');
app.listen(PORT, (error) =>
{
if(!error)
console.log('Server Listenining on: ', {PORT})
else
console.log("Error Found in Application: ", error)
});
app.use("/www", express.static(__dirname + "/www"));
app.get('/', (req,res) => {
res.sendFile(path.join(__dirname, '/www/index.html'));
});
app.get('/favicon.ico', (req,res) => {
res.sendFile(path.join(__dirname, '/www/favicon.ico'));
});
We first define our constants to configure the app. We set the port the app will listen on to be the PORT const we defined. Then we create an error handling function that will log "Error found in application" [Error], where [Error] will be the error caught, whenever we cause an error. If there are no errors then we log the port the server is listening on to the console, and can navigate to our server at http://localhost:43451, if everything has gone well then it will load our file app/www/index.html.
<!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/x-icon" href="/www/img/favicon.ico">
<title>Our Server</title>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
</head>
<body>
<div id="our-id">
<p>This is our first paragraph!</p>
</div>
</body>
</html>
And there is the beginning of a simple express server