create file name server

This commit is contained in:
buzzcode2007 2025-03-08 10:54:43 +00:00
parent 5a1be2a972
commit 638d915654
2 changed files with 63 additions and 1 deletions

62
names.final.js Normal file
View file

@ -0,0 +1,62 @@
let express = require('express'); require('dotenv').config(); let app = express();
const bodyParser = require(`body-parser`);
class ServerForNames {
#paths = {
"API": {
"name": "/name"
},
"pages": {
"default": "/views/index.html"
},
"static": {
"assets": "/public"
}
}
/* Log all requests.
REQUEST (object): The request.
*/
log(REQUEST) {
console.log(REQUEST.method, REQUEST.url, REQUEST.ip);
}
/* Echo.
PARAMETERS (object): The name parameters.
returns: (object) the formatted repeat response
*/
parse(PARAMETERS) {
let RESPONSE = {"name": [PARAMETERS["first"], PARAMETERS["last"]].join(` `)};
return (RESPONSE);
}
/* Create the response.
REQUEST (object): The request object.
RESPONSE (object): The response object.
*/
respond(REQUEST, RESPONSE) {
RESPONSE.json(this.parse(REQUEST.body || REQUEST.query));
}
/* Accept requests. */
accept() {
app.use(bodyParser.urlencoded({extended: false}));
app.use((REQUEST, RESPONSE, next) => {this.log(REQUEST); next();})
app.use(this.#paths['static'][`assets`], express.static(__dirname + this.#paths['static'][`assets`]));
app.route(`/`).get((REQUEST, RESPONSE) => {RESPONSE.sendFile(__dirname + this.#paths[`pages`]['default'])});
[`get`, `post`].forEach((METHOD) => {
app.route(this.#paths[`API`][`name`])[METHOD]((REQUEST, RESPONSE, next) => {this.respond(REQUEST, RESPONSE);});
});
}
constructor() {
this.accept();
}
}
new ServerForNames();
module.exports = app;

View file

@ -4,7 +4,7 @@
* ***************************************************/
const bGround = require('fcc-express-bground');
const myApp = require('./scripts/names');
const myApp = require('./names.final');
const express = require('express');
const app = express();