"Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a
Database"
In the fast-paced and interconnected digital landscape,
Application Programming Interfaces (APIs) have
emerged as the driving force behind seamless connectivity,
collaboration, and innovation. APIs act as bridges between different software
systems, allowing them to communicate, share data,
and perform functions that enhance the overall user experience. As
businesses strive for efficiency and adaptability, unlocking the
power of APIs has become a strategic imperative.
How to Obtain a Dropdown Menu and Store it in a Database
Here, we will start how to gain dropdown menu via API nodejs express and when user choose any menu then data will store in Mongodb Database. In nodejs there is potential to make a API with the help of any End-point like you know about API how is look like !! right.
Let's define first how is Actually Nodejs, expressjs, after that we will see about mongodb and how can we store it. Okay!!!
Nodejs is a powerful, open-source, server-side runtime environment that allows developers to build scalable and high-performance network applications. It is built on the chrome V8 javascript runtime and uses an event-driven, such as web servers, chat applications, and online gaming platforms.
Here are key aspects of Node.js:
JavaScript Runtime:
Node.js allows developers to use JavaScript for
server-side scripting. This unifies the language used for both client-side and
server-side development, which can streamline the development process.
What is MongoDB
MongoDB is a popular open-source NoSQL (non-relational) database management system. NoSQL means no structure like it is look like an object while in SQL it is a structure query language like SELECT CustomerName, City FROM Customers; (The SELECT statement is used to select data from a database.) But NoSQL database is useless...NOT completely because of whenever we want add extra column in database then it is possible through NoSQL MongoDB.
MongoDB installation - CLICK HERE
MongoDB Basic Command -
CLICK HERE
About MongoDB vs SQL - CLICK HERE
CRUD in MongoDB - CLICK HERE
Object Like -
{ "_id": { "$oid": "659ad46e0382148123c82841" }, "name": "moto G60", "brand": "motorola", "price": 16500, "category": "mobile" }
MongoDB is a type of database that helps store and manage
large amounts of data in a flexible and scalable way. Unlike SQL, MongoDB
doesn't require a fixed structure for the data, allowing you to store
information in a more versatile format.
- MongoDB is a NoSQL database.
- The data stored in a collection
- Collection don't have row and columns
- Data is stored in the form of object.
Reactjs Application
Here, we will start from reactjs application and create a new project, after
that in src folder create a new folder like components and inside this
components folder create a file called as Dropdown.jsx. In App.jsx
file, we need to add Dropdown.jsx file add to the app.jsx file.
Now its coding time
Dropdown.jsx
import React from 'react' function Dropdown() { return ( <div> <p>Dropdown</p> </div> ); } export default Dropdown;
Now create a three useState();
import React, { useEffect, useState } from "react"; function Dropdown() { const [designation, setDesignation] = useState(); const [dropdownData, setDropdowndata] = useState([]); const [selectedOption, setSelectedOption] = useState(""); return ( <div> <p>Dropdown</p> </div> ); } export default Dropdown;
now this some we are trying to create a interface of dropdown menu and submit button
import React, { useEffect, useState } from "react"; function Dropdown() { const [designation, setDesignation] = useState(); const [dropdownData, setDropdowndata] = useState([]); const [selectedOption, setSelectedOption] = useState(""); return ( <div class="grid grid-cols-1 ml-20 mt-[50px] mr-20 "> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="Designation" > Designation </label> <select value={selectedOption} onChange={(e) => setSelectedOption(e.target.value)} className="dropdown-button w-full bg-white p-2 border text-xs/[12px] py-3 px-4 " > <option value={designation} onChange={(e) => setDesignation(e.target.value)} disabled > Select an option </option> {dropdownData.map((option) => ( <option key={option} value={option}> {option} </option> ))} </select> {selectedOption && <p>You selected: {selectedOption}</p>} </div> <button className="bg-blue-600 text-white pt-2 pb-2 pr-3 pl-3 mt-3 ml-3" onClick={handleSubmit} > Add Employee </button> </div> </div> </div> ); } export default Dropdown;
Handle the data but this time check our code very carefully becuase of we have to used API and fetch the Dropdown menu from API nodejs. okay!!
complete reactjs application
import axios from "axios"; import React, { useEffect, useState } from "react"; function Dropdown() { const [designation, setDesignation] = useState(); const [dropdownData, setDropdowndata] = useState([]); const [selectedOption, setSelectedOption] = useState(""); const handleSubmit = async () => { try { const response = await axios.post( "http://localhost:8000/createEmployee", { designation: selectedOption, } ); if (response.status === 200) { console.log("Status is good"); } console.log(response); console.log(response.data); setDesignation(''); } catch (error) { console.log("Error adding employeeData", error.message); } }; useEffect(() => { const fetchData = async () => { try { const response = await axios.get("http://localhost:8000/api/dropdown"); setDropdowndata(response.data); } catch (error) { console.log("Error fetching dropdown data: ", error.message); } }; fetchData(); }, []); return ( <div> <div class="grid grid-cols-1 ml-20 mt-[50px] mr-20 "> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="Designation" > Designation </label> <select value={selectedOption} onChange={(e) => setSelectedOption(e.target.value)} className="dropdown-button w-full bg-white p-2 border text-xs/[12px] py-3 px-4 " > <option value={designation} onChange={(e) => setDesignation(e.target.value)} disabled > Select an option </option> {dropdownData.map((option) => ( <option key={option} value={option}> {option} </option> ))} </select> {selectedOption && <p>You selected: {selectedOption}</p>} </div> <button className="bg-blue-600 text-white pt-2 pb-2 pr-3 pl-3 mt-3 ml-3" onClick={handleSubmit} > Add Employee </button> </div> </div> </div> </div> ); } export default Dropdown;
const response = await
axios.post("http://localhost:8000/createEmployee");
const response =
await axios.get("http://localhost:8000/api/dropdown");
NOTE :- You can add these lines only when you have
created the API in NodeJS.
in App.jsx file, we will import our dropdown.jsx file.
finally run this application. By this command npm run dev
NOTE :- At this time please ignore Dropdown data as we have not created
the API yet.
MongodDB Database
Why we are building mongodb database and collection(table) because we will need conection URL to connect in nodejs and also we will need database name and collection name.
after installing mongodb compass in your system simply open it and copy the url and click connect button.
After click on button then we have some command for you, by the use this command you can simply create database and its collection .
- show dbs (database check)
- use optionmenu (create db)
- db.createCollection('employeedatas') (create table)
- show collections (check table - by default we don't any data because of not
yet wr create a any data)
Nodejs - Expressjs API
Here, first we need to install to some pkg in server side application because of we need to some pkg for make API purpose.
npm init
npm i express
npm i mongodb (mongodb
connection)
npm i cors
npm i nodemon -g (for run our
server side application, -g means globaly)
npm i mongoose (it is driver for connection of nodejs and mongodb)
Create a new folder called as server outside of reactjs application project folder and open cmd prompt in server directory and install one by one pkg.
server.js
First, we will create a folder called as mongodb and inside this folder
we will create a file called as config.js
const mongoose = require('mongoose') mongoose.connect("mongodb://127.0.0.1:27017/optionmenu")
optionmenu - it is our database name.
mongodb://127.0.0.1:27017/ - it is our connection url when open mongodb
you get it.
const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); app.use(express.json()); const DropDownOptions = ['HR', 'Manager', 'Employee']; app.get('/api/dropdown', (req, resp) => { resp.json(DropDownOptions) }) app.listen(8000, () => { console.log('Server is running on port 8000'); })
Then simply run nodemon server.js file in vs code terminal.
Now we will check in our postman for dropdown data is coming or not.
Yupee!! We got it.
again we will create a new API for uploading the data when user select dropdown menu options and store it.
but before creating a new API, lets make schemas and model. For this first create a new folder called as schema and inside this folder create a file employee.js.
1. importing the mongoose.
This line imports the Mongoose library, which is a popular ODM (Object Data Modeling) library for MongoDB and Node.js. It provides a way to define schemas, interact with the MongoDB database, and perform various operations.
const mongoose = require('mongoose');
2. Defining a Mongoose Schema:
const employeeSchema = new mongoose.Schema
({
designation: String,
})
This code creates a Mongoose schema for the "employeeData" collection. The schema specifies that documents in this collection should have a field named "designation" of type String. This is a basic example, and in a real-world scenario, you would include more fields and specify their types.
3. Exporting the Mongoose Model
module.exports = mongoose.model('employeeData', employeeSchema)
The code exports a Mongoose model based on the defined
schema. The mongoose.model function takes two arguments:
The first
argument ('employeeData') is the name of the MongoDB collection.
This name is case-sensitive and is typically given in the singular form.
The second argument (employeeSchema) is the schema definition. By
exporting this model, you can use it in other parts of your application to
interact with the MongoDB collection named "employeeData."
app.post('/createEmployee', async (req, resp) => { try { const { designation } = req.body; const newEmployee = new employee({ designation }); await newEmployee.save(); resp.status(200).json({message: 'Employee created successfully'}) } catch(error){ resp.status(500).json({message: 'Internal Server Error'}); } });
Server.js
const express = require('express'); require('./mongodb/config') const employee = require('./schema/employee') const cors = require('cors'); const app = express(); app.use(cors()); app.use(express.json()); app.post('/createEmployee', async (req, resp) => { try { const { designation } = req.body; const newEmployee = new employee({ designation }); await newEmployee.save(); resp.status(200).json({message: 'Employee created successfully'}) } catch(error){ resp.status(500).json({message: 'Inernal Server Error'}); } }); const DropDownOptions = ['HR', 'Manager', 'Employee']; app.get('/api/dropdown', (req, resp) => { resp.json(DropDownOptions) }) app.listen(8000, () => { console.log('Server is running on port 8000'); })
Finally our time is come.
Disclaimer
All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.