Installing and Launching a Backend in Express.js
This document provides a step-by-step guide on how to install and launch a backend using Express.js. Express is a web framework for Node.js that allows you to build web applications and services easily and quickly.
Step 1: Set Up the Environment
Create a New Project
Open your terminal and run the following commands to create a new directory and navigate into it:
mkdir express-backend
cd express-backend
Initialize a New Node.js Project
Run the following command and follow the prompts to create a package.json file:
npm init -y
Install Express
Run the following command to install Express.js in your project:
npm install express
Create api key
Create a .env file in the root of your project and put any arbitrary API_KEY
API_KEY=rnmdfgdfwer34234asdfsdf41mp&*cm6hw+tm0!a^sdfsdfwe35uqx1z4
Step 2: Create the Express Server
Create the Server file
Create a file named server.js in the root of your project and add the following code:+
require("dotenv").config();
const express = require("express");
const app = express();
const PORT = 3000;
// Middleware to parse JSON request bodies
app.use(express.json());
app.use((req, res, next) => {
const apiKey = req.headers["api_key"]; // Cambia según el encabezado que uses
if (apiKey && apiKey === process.env.API_KEY) {
next(); // Si la API Key es válida, continúa con la siguiente función de middleware
} else {
res.status(403).send("Forbidden: Invalid API Key"); // Responde con un error 403 si la API Key es inválida
}
});
// POST endpoint to sum two numbers
app.post("/sum", (req, res) => {
const { arg_1, arg_2 } = req.body; // Extract arg_1 and arg_2 from the request body
// Validate that both arguments are numbers
if (typeof arg_1 !== "number" || typeof arg_2 !== "number") {
return res.status(400).json({
status: "error",
message: "Both arg_1 and arg_2 must be numbers.",
});
}
const result = arg_1 + arg_2; // Sum the two numbers
// Return the response in the desired format
res.json({
status: "success",
data: {
result: result,
},
});
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 3: Run the Server
Run the following command in the terminal:
node server.js
Note: Ensure that your server's IP address is accessible from the outside to allow the Oracle to interact with it. You may need to configure your firewall or router settings accordingly.