What we will be doing
We will make our server send the get request to someone's server and get a response back from someone's server to our server. We will be using "Public API" via Axios.
Axios
What is Axios
Axios is a promise-based HTTP Client for node.js and the browser.
Promise
A promise is a special JavaScript object that links the “producing code” and the “consuming code” together.
A “producing code” that does something and takes time. For instance, some code that loads the data over a network.
A “consuming code” that wants the result of the “producing code” once it’s ready. Many functions may need that result.
NOTE
For more information on Axios refer to this link:- https://axios-http.com/docs/intro
Installing Axios
npm install axios
Let's understand how we can use "Axios" with an example
Steps
Install axios, express, nodemon, body-parser
npm i express axios nodemon body-parser
Now make a file name index.js. Make a folder views and inside views make an index.ejs file. Make a folder public and inside public make another folder named styles and inside styles make file main.css. Your file structure should be look as shown below
Now start the server by writing nodemon index.js in terminal
import express from "express"; import bodyParser from "body-parser"; import axios from "axios"; const app = express(); const port = 3000; app.get("/", function (req, res) { res.render("index.ejs"); }) app.listen(port, () => { console.log(`Server running on port: ${port}`); });
Now we will make a normal and simple structure in index.ejs using HTML and CSS.
<!-- index.ejs --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/styles/main.css"> <title>Axios</title> </head> <body> <div class="container"> <h1>Let's find something!!</h1> <form> <select name="type" class="form-select"> <option value="" data-display="Select">Random type</option> <option value="education">Education</option> <option value="charity">Charity</option> <option value="recreational">Recreational</option> <option value="relaxation">Relaxation</option> <option value="busywork">Busywork</option> <option value="social">Social</option> <option value="diy">DIY</option> <option value="music">Music</option> </select> <select name="participants" class="form-select"> <option value="">Any number of people</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <button type="submit" class="form-submit">Go</button> </form> </div> </body> </html>
/* main.css */ *, *::after, *::before { margin: 0; padding: 0; box-sizing: border-box; } html { height: 100%; } /* ------------ */ body { font-family: monospace; height: 100%; } h1 { width: 100%; margin-bottom: 40px; } /* ------------ */ .container { height: 100%; width: 100%; max-width: 570px; margin: 0 auto; padding: 60px; display: flex; flex-direction: column; justify-content: center; align-items: center; } /* ------------ */ .form { width: 100%; display: grid; grid-template-columns: 1fr 1fr 80px; grid-column-gap: 10px; } .form-submit { outline: none; border: 1px solid rgb(232, 232, 232); background-color: white; border-radius: 5px; cursor: pointer; font-family: monospace; font-size: 14px; line-height: 36px; } .form-submit:focus { box-shadow: 0 0 0 0.5px rgb(153, 153, 153); } /* ------------ */ @media (max-width: 620px) { .container { width: 100%; max-width: 100%; margin: 0 auto; padding: 60px 20px; } .form { width: 100%; display: grid; grid-template-columns: 1fr; grid-gap: 10px; } }
Now add the action and method in index.ejs
<!-- index.ejs --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/styles/main.css"> <title>Axios</title> </head> <body> <div class="container"> <h1>Let's find something!!</h1> <form action="/" id="form" class="form" method="POST"> <select name="type" class="form-select"> <option value="" data-display="Select">Random type</option> <option value="education">Education</option> <option value="charity">Charity</option> <option value="recreational">Recreational</option> <option value="relaxation">Relaxation</option> <option value="busywork">Busywork</option> <option value="social">Social</option> <option value="diy">DIY</option> <option value="music">Music</option> </select> <select name="participants" class="form-select"> <option value="">Any number of people</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <button type="submit" class="form-submit">Go</button> </form> </div> </body> </html>
Till now you will see below page
Middleware functions are added using app.use() in index.js
//index.js //This middleware serves static files from the "public" directory, such as CSS or JavaScript files app.use(express.static("public")); //This middleware parses incoming request bodies in URL-encoded form. app.use(bodyParser.urlencoded({ extended: true }));
Now handle GET request.
\=>When a GET Request is sent to root i.e.; "/", the server sends an HTTP Request to an external API using axios.
\=>If the request is successful it will retrieve data and render index.ejs and If there is an error, it will show an error message.
//index.js
app.get("/", async (req, res) => {
try {
const response = await axios.get("https://bored-api.appbrewery.com/random");
const result = response.data;
console.log(result);
res.render("index.ejs", { data: result });
} catch (error) {
console.error("Failed to make request:", error.message);
res.render("index.ejs", {
error: error.message,
});
}
});
Now handle POST request
\=>When POST request is made server expects data from request body i,e:, it expects type and participants from the body i,e;, from form.
\=>It then sends an HTTP request to another external API with query parameters based on the extracted values.
\=>If the request is successful, it randomly selects an activity from the API response and renders an EJS template called "index.ejs" with the selected activity and if not successful, it renders the error message.
app.post("/", async (req, res) => {
try {
console.log(req.body);
const type = req.body.type;
const participants = req.body.participants;
const response = await axios.get(
`https://bored-api.appbrewery.com/filter?type=${type}&participants=${participants}`
);
const result = response.data;
console.log(result);
res.render("solution.ejs", {
data: result[Math.floor(Math.random() * result.length)],
});
} catch (error) {
console.error("Failed to make request:", error.message);
res.render("index.ejs", {
error: "No activities that match your criteria.",
});
}
});
Now we will do EJS conditional rendering
\=>If locals.data is available then it will display the randomly selected activity.
\=>If locals.error is available then it will display the error message.
\=>The value of activity, type, participants is display using EJS Tags.
<!-- index.ejs --> <section id="cards" class="cards"> <%if (locals.data) {%> <article class="card-item"> <h2 class="card-activity"> <%=data.activity %> </h2> <div class="card-info"> <span class="card-type"> <%=data.type%> </span> <span class="card-participants"> participants: <%= data.participants%> <span class="card-number"></span> </span> </div> </article> <%}%> <%if (locals.error) {%> <div id="tag-error" class="tag-error"> <%=error%> </div> <%}%> </section>
/*main.css*/ .cards { display: flex; margin: 20px 0; width: 100%; } .card-item { width: 100%; padding: 5px 20px 20px; border: 1px solid rgb(232, 232, 232); background-color: white; border-radius: 5px; } .card-info { margin-top: 40px; display: flex; justify-content: space-between; } .card-activity { line-height: 1.2; margin-top: 10px; } .tag-error { width: 100%; text-align: center; } /* ------------ */ .is-element-hidden { display: none; }
Now our web application is ready
Resources
You will get source code from here:- https://github.com/hetashridk/Axios
Conclusion
In this article, we have learn what is Axios, how we can use Axios for HTTP module and how we easily implement it.