-->

ABOUT US

Our development agency is committed to providing you the best service.

OUR TEAM

The awesome people behind our brand ... and their life motto.

  • Kumar Atul Jaiswal

    Ethical Hacker

    Hacking is a Speed of Innovation And Technology with Romance.

  • Kumar Atul Jaiswal

    CEO Of Hacking Truth

    Loopholes are every major Security,Just need to Understand it well.

  • Kumar Atul Jaiswal

    Web Developer

    Techonology is the best way to Change Everything, like Mindset Goal.

OUR SKILLS

We pride ourselves with strong, flexible and top notch skills.

Marketing

Development 90%
Design 80%
Marketing 70%

Websites

Development 90%
Design 80%
Marketing 70%

PR

Development 90%
Design 80%
Marketing 70%

ACHIEVEMENTS

We help our clients integrate, analyze, and use their data to improve their business.

150

GREAT PROJECTS

300

HAPPY CLIENTS

650

COFFEES DRUNK

1568

FACEBOOK LIKES

STRATEGY & CREATIVITY

Phasellus iaculis dolor nec urna nullam. Vivamus mattis blandit porttitor nullam.

PORTFOLIO

We pride ourselves on bringing a fresh perspective and effective marketing to each project.

Showing posts with label Web Developing. Show all posts
Showing posts with label Web Developing. Show all posts
  • Dockerfile, Custom Images, and Environment Variables Explained for Beginners

     

    Dockerfile, Custom Images, and Environment Variables Explained for Beginners

     

     

    Dockerfile, Custom Images, and Environment Variables Explained for Beginners



    Docker is one of the most important technologies in modern DevOps, cloud computing, and software deployment. After learning Docker Images and Containers, the next step is understanding Dockerfiles, building custom images, and using environment variables. 
    Learn Dockerfile, custom Docker image creation, and environment variables with practical examples. A beginner-friendly Docker guide for DevOps and System Engineers.

    In this guide, you'll learn these concepts with practical examples.


    What is a Dockerfile?



    A Dockerfile is a text file that contains instructions for building a Docker image. Instead of manually configuring containers every time, you can define all steps inside a Dockerfile and create reproducible images.

    Example:

     

    dockerfile
    FROM nginx
    COPY index.html /usr/share/nginx/html/index.html
      




    In this example:

    • * FROM nginx uses the Nginx image as the base image.
    • * COPY copies a webpage into the Nginx web server directory.


    Docker reads these instructions and builds a custom image.



     Common Dockerfile Instructions



    FROM

    • Specifies the base image.
    • FROM ubuntu



     WORKDIR

    Sets the working directory inside the container.


    • WORKDIR /app



     COPY

    Copies files from the host machine into the container.

    • COPY . .



    RUN

    Executes commands during image creation.


    • RUN npm install



    CMD

    Defines the default command executed when the container starts.


    • CMD ["node","server.js"]



    Building Custom Docker Images

    Let's create a simple custom image.

     

    Project Structure

     

    text
    project/
    │
    ├── Dockerfile
    ├── index.html
    
    

     



    Dockerfile


    • FROM nginx
    • COPY index.html /usr/share/nginx/html/index.html




    Build the Image



    Run the following command inside the project directory:

    • docker build -t mywebsite . 

     

     
    Explanation:
     

    • docker build creates a Docker image.
    • -t assigns a tag or image name.
    • mywebsite is the image name.
    • .  represents the current directory.



     

    Verify the Image


    • docker images



    You should see:


    • REPOSITORY
    • mywebsite




    Run the Custom Image


    • docker run -d -p 8080:80 mywebsite


    Open:


    • http://localhost:8080


    Your custom webpage should now be visible in the browser.

     

     

     

    What Are Environment Variables?



    Environment variables allow you to pass configuration values to containers without modifying application code.

    This makes applications easier to manage and deploy.

    Example:


    • docker run -e APP_NAME=HackingTruth nginx



    Here:

     

    • APP_NAME=HackingTruth



    is an environment variable available inside the container.


     

    Multiple Environment Variables

     

     

    docker run \
    -e DB_HOST=localhost \
    -e DB_USER=root \
    -e DB_PASSWORD=password \
    myapp
    
    

     

    This approach is commonly used for:

    • * Database credentials
    • * API keys
    • * Application settings
    • * Deployment configuration



    Defining Environment Variables in Dockerfile


    You can also define variables directly inside a Dockerfile.


    • FROM ubuntu
    • ENV APP_NAME=HackingTruth
    • ENV VERSION=1.0



    Build the image:

    • docker build -t myapp .



    Run the container:

    • docker run myapp



    The environment variables will be available inside the container.


    Why Use Dockerfiles and Environment Variables?



    Dockerfiles provide:

    • * Consistent deployments
    • * Reproducible environments
    • * Easier automation



    Environment variables provide:

    • * Better configuration management
    • * Improved security practices
    • * Easier deployment across environments


    Together, they form the foundation of modern containerized applications.


    Conclusion



    Understanding Dockerfiles, custom image creation, and environment variables is essential for anyone learning Docker, DevOps, Cloud Computing, or System Administration.

    By mastering these concepts, you'll be able to create reusable Docker images, automate deployments, and configure applications efficiently. These skills are widely used in real-world production environments and are frequently asked about in DevOps and System Engineer interviews.



  • docker-installation-images-containers-port-mapping-guide


    docker-installation-images-containers-port-mapping-guide

     


    Docker is a platform that allows developers and system administrators to package applications and their dependencies into containers. Containers are lightweight, portable and run consistently across different computing environment.



    Docker Learning Path for You



    Week 1

    • Install Docker 
    • Containers vs Images 
    • Pull images 
    • Run containers 
    • Port mapping 



    Week 2 

    • Dockerfile 
    • Build custom images 
    • Environment variables 



    Week 3 


    • Docker Volumes 
    • Docker Networks 
    • Multi-container 
    • applications 



    Week 4 

    • Docker Compose 
    • Deploy React/Node applications 
    • Container troubleshooting 



    But we will start from week 1 module and try to answer the interview level question also 

     

     Install Docker 

     

     For installing the docker via docker-desktop and via wsl linux. you can choose any of the them or both so check it here for previously we have done this part and many things you can learn from other blog article.

     

    Click Here 

     

    Containers vs Images


    This is one of the most common Docker interview questions.


    • Docker Image


    An Image is like a blueprint or template.



    Think of it like:

    Windows ISO File
         ↓
    Install Windows
         ↓
    Running Windows OS
      



    Similarly:
    Docker Image
        ↓
    Run Image
        ↓
    Docker Container
    




    Examples of Images:

    • nginx
    • ubuntu
    • mysql
    • node



    View downloaded images:

    • docker images




    Example output:


    docker-installation-images-containers-port-mapping-guide

     

    Docker Container



    A Container is a running instance of an image or Containers are standardized software units that package code and dependencies together, ensuring an application runs quickly and reliably across any computing environment. 


    Example:

    • docker run nginx


    Docker:

    • Checks for nginx image
    • Downloads it if missing
    • Creates container
    • Starts container


    View running containers:  list running container and verify 

    docker ps

     

     docker-installation-images-containers-port-mapping-guide

     

     

     Interview Answer


    What is the difference between Image and Container?



    Image


    • Read-only template
    • Used to create containers
    • Similar to an ISO file



    Container

    • Running instance of an image
    • Has its own process and network
    • Similar to an installed/running operating system

     

     

    Pull Images



    What is Pull?

    Downloading an image from Docker Hub to your local machine.

    Example:

    docker pull nginx


    Docker downloads:

    • nginx:latest
    • Pull Ubuntu
    • docker pull ubuntu



    Check downloaded images:

    • docker images
    • Pull Specific Version
    • docker pull nginx:1.27




    Why?


    In production we often use specific versions instead of latest.


    Interview Question



    What does docker pull do?

    Answer:

    docker pull downloads an image from a registry such as Docker Hub to the local Docker host.

    like this hello-world repo or registry -





    docker-installation-images-containers-port-mapping-guide



     Port Mapping


    This is extremely important.



    Without Port Mapping


    Run nginx:

    • docker run nginx
    • Container runs internally.
    • You cannot access it from your browser.


    With Port Mapping

    • docker run -d -p 8080:80 nginx






    Meaning:

    • Host Machine Port = 8080
    • Container Port = 80



    Visualization:


    Your Laptop
    localhost:8080
            │
            ▼
    Docker Container
    Port 80 (Nginx)



    Test


    Open browser:

    http://localhost:8080

    You should see:

    Welcome to nginx!



    docker-installation-images-containers-port-mapping-guide






    Another Example


    Node.js app running on port 3000 inside container:

    • docker run -d -p 3000:3000 myapp



    Meaning:

    • Host 3000 → Container 3000
    • Check Port Mapping
    • docker ps



    Example:

    PORTS

    • 0.0.0.0:8080->80/tcp



    Meaning:

    Host Port 8080
               ↓
    Container Port 80


     

     

    Commands You Must Remember



    Pull image:

    • docker pull nginx


    List images:

    • docker images


    Run container:

    • docker run nginx


    Run in background:

    • docker run -d nginx


    Port mapping:

    • docker run -d -p 8080:80 nginx


    Running containers:

    • docker ps



    All containers:

    • docker ps -a





    Before moving to Week 2, make sure you can confidently explain:

    ✅ What is Docker?
    ✅ What is an Image?
    ✅ What is a Container?
    ✅ What is Docker Hub?
    ✅ What is docker pull?
    ✅ What is port mapping?
    ✅ Difference between docker ps and docker images?
    ✅ Meaning of 8080:80?

     

    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. 
     
     
     
     
     
  • docker-images-vs-containers-complete-beginners-guide

     

    docker-images-vs-containers-complete-beginners-guide

     

    docker-images-vs-containers-complete-beginners-guide


    What is the docker, and how would you use it in a system engineering role ?

    Docker is a platform that allows developers and system administrators to package applications and their dependencies into containers. Containers are lightweight, portable and run consistently across different computing environment.


    How docker is used in system engineering:

    1. Containerization: Docker packages an application with all its dependencies into a single container, which can be run on any system that supports docker. This simplifies deployment and eliminate dependency conflicts.

    2. Environment Isolation: Each containers is isolated, providing a consistent environment for applications regardless of the underlying host system. This helps with environment replication across development, stagging and production.

    3. CI/CD pipelines: (Continuous Integration and Continuous Delivery/Development) Docker containers are widely used in CI/CD  pipelines to ensure consistent testing, building and deployment environment.

    4. Scalability: Dockers containers can be easily scaled up or down in a Kubernetes or docker swarm environment.




    Core components of Docker



    It is responsible for the overall functioning of the docker platform and docker engine is a client-server based application and consists of 3 main components.

    - Server
    - REST API
    - Client


    - Server -> The server runs a daemon known as dockerd (Docker Daemon), which is nothing but a process. It is responsible for creating and managing docker images, containers, networks and volumes on the Docker platform.

    - REST API - The REST API specifies how the applications can interact with the server and instruct it to get their job done.

    - The client is nothing but a command line interface, that allows users to interact with docker using the commands.




    Docker Terminology 


    Docker Images and Docker containers are the two essential things that you will come across daily while working with docker.

    In simple terms, a docker image is a template that contains the application, and all the dependencies required to run that application on docker.

    On the other hand, as started earlier, a docker container is a logical entity. In more precise terms, it is a running instance of the docker image.


    What is Docker Hub? 


    Docker hub is the official online repository where you could find all the docker images that are available for us to use also allows us to store and distribute our custom images as well if we wish to do so. We could also make them either public or private, based on our requirements.


    What is Docker image?

    Docker image is actually an executable file that file inside instruction for which types of container we should make so using one image we can create multiple container.

    Image is basically like a static screenshot or static snapshot of what the code and the dependencies or what the local development environment look like.

    The relation between Docker and Container like the same as Class (class - how look like object create a blueprint of code) and Object in between of relation.

    Docker image is giving a blue print of how container look like in MAC, Linux, Windows.


    Container 


    Docker is platform or services that useful for creating a container. container i

    • Portable - Portable means we can share data one machine to another machine is become to easier share code as well as dependencies with their development team.
    • Lightweight - Lightweight means easier to build, update and destroy and if we want install extra addon dependencies then we can install in same container.



    OR

    why we make container so what should i do for making container ?


    • Containers are standardized software units that package code and dependencies together, ensuring an application runs quickly and reliably across any computing environment.

     

    after making Docker Container and add some dependencies or else so we should make again docker image ?



    Yes, you need to create a new image if you want to save those changes permanently. Containers are temporary and disposable. Any changes you make directly inside a running container will be lost forever if that container is stopped, deleted, or restarted.


    You have two main ways to handle this, depending on your goal:

     

    Method: Save the Live Container (Quick Fix)



    If you spent a lot of time configuring a running container manually and do not want to lose your work immediately, you can take a snapshot of it.

    Find your running container ID:

    • bashdocker ps


    Use code with caution.Commit the changes to create a brand new image directly from that running container:

    • bashdocker commit CONTAINER_ID your-new-image-name

     

     

    How to install and run docker desktop

     

    Step 1: Check Requirements

    Option A: Docker Desktop (Recommended)

    Requirements:

    • Windows 10 64-bit
    • At least 4 GB RAM (8+ GB recommended)
    • Hardware virtualization enabled in BIOS
    • WSL 2 support


    First, open PowerShell as Administrator and check:

    systeminfo


    Look for:

    • Hyper-V Requirements: Yes
    • Virtualization Enabled In Firmware: Yes


    Step 2: Enable WSL 2

    Open PowerShell as Administrator:

    wsl --install





    After completing task 1 like according to image 1(above image) it will ask for reboot the system then after rebooting the system (according to image 2 - below) it will automatically popup a cmd and run this wsl linux.



    docker-images-vs-containers-complete-beginners-guide




    Restart your PC.

    Verify:

    wsl --status


    You should see WSL version 2 installed.

     

     


     

    Step 3: Download Docker Desktop



    Go to:

    Docker Desktop for Windows

    Download the installer.



    Step 4: Install Docker Desktop



    Run the installer.

    During installation:

    ✅ Use WSL 2 instead of Hyper-V (recommended)
    ✅ Add Docker Desktop shortcut

    Restart if prompted.

     

     

     

    docker-images-vs-containers-complete-beginners-guide

     

    Step 5: Start Docker



    Launch Docker Desktop.

    Wait until Docker reports:

    • Docker Engine running



    docker-images-vs-containers-complete-beginners-guide



    Step 6: Verify Installation



    Open PowerShell:

    • docker --version


    Example output:

    • Docker version 28.x.x


    Check Docker engine:

    • docker info

     

    NOTE -  some useful URLs you can check here  

     

    • https://hub.docker.com/_/hello-world
    • https://app.docker.com/accounts/whoiskumaratul

     

    Step 7: Run Your First Container

     

    To run this your first container hello world docker from URL - you can check here - Docker Hello World 


    Test Docker with:

    • docker run hello-world


    If successful, you'll see a welcome message.


    So, for this we will pull first - docker pull hello-world

      

     

    docker-images-vs-containers-complete-beginners-guide

     

     Then run container and you can see in the docker desktop UI there will be create docker image and docker container 

     

    • docker run hello-world

     

     

    docker-images-vs-containers-complete-beginners-guide

     

     

    Docker Ubuntu

    When we installed wsl ubuntu you have noticed in your local directory - linux section is there 

     

     

    docker-images-vs-containers-complete-beginners-guide

     

     you can run this via Linux ubuntu - try this command docker run -it ubuntu 

     -it -> we want to run in interactive mode

     

     

    docker-images-vs-containers-complete-beginners-guide

     

     Now we can check directory and create new folder, file because we are in linux directory 

     

     

    docker-images-vs-containers-complete-beginners-guide

     

    Stop container

    • docker stop <container_id>



    Remove container

    • docker rm <container_id>



    Remove image

    • docker rmi <image_name>

     

     

     


     

    Step 8: Run an Nginx Web Server



    Pull and run Nginx:

    • docker run -d -p 8080:80 nginx

     

     

     

    docker-images-vs-containers-complete-beginners-guide

     

     

    Verify:

    • docker ps




      

    Open browser:

    • http://localhost:8080


    You should see the Nginx welcome page.

     

     

    docker-images-vs-containers-complete-beginners-guide

     

    Essential Docker Commands for Interviews



    List running containers

    • docker ps



    List all containers

    • docker ps -a



    List images

    • docker images



    Stop container

    • docker stop <container_id>



     

    docker-images-vs-containers-complete-beginners-guide

     

     

     

     

    Remove container

    • docker rm <container_id>



    Remove image

    • docker rmi <image_name>

     

     

    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.


  • Difference between Yarn and Npm

     

    Difference between Yarn and Npm

     

     

    Yarn and npm (Node Package Manager) are package managers for JavaScript. They help developers manage project dependencies (libraries and tools that a project needs to function). Here are some key differences between Yarn and npm:

     

    Yarn

     

    Speed and Performance


    # Yarn: Known for its faster performance compared to older versions of npm. Yarn achieves this speed through parallelized operations. It downloads packages in parallel and uses a global cache to reduce the need for repeated downloads.

    # npm: While older versions of npm were slower, the newer versions (npm 5 and above) have improved significantly in terms of speed and performance. npm also introduced a caching mechanism, but its operations are not as parallelized as Yarn’s.

     

    2. Lock Files


     # Yarn: Uses a `yarn.lock` file to lock the versions of the packages that are installed. This ensures that the same versions of dependencies are installed every time the project is built, leading to more consistent builds. 

     


     

     

    # npm: Uses a `package-lock.json` file, which serves a similar purpose as Yarn’s `yarn.lock`. It was introduced in npm version 5 to improve the reliability of builds by ensuring that the exact same dependencies are installed for every build.

     

     


     

     

     3. Installation of Dependencies


     # Yarn: Installs dependencies from the top-level down, which can lead to better performance and fewer conflicts.
     

    # npm: Traditionally, npm installed dependencies recursively, which could lead to larger `node_modules` directories and more conflicts. Recent versions of npm (npm 7+) use a similar approach to Yarn, flattening the `node_modules` hierarchy.

     

    4. Security
     

    # Yarn: Has a built-in feature to check for vulnerabilities in dependencies using the `yarn audit` command.

    # npm: Also provides a similar feature with the `npm audit` command. In addition, npm automatically checks for vulnerabilities during installation and provides a summary.
     

     

    5. Community and Ecosystem
     

    # Yarn: Gained popularity quickly after its release and has a strong community. It is backed by Facebook, which contributed to its initial popularity.

    # npm: Has been around longer and has a larger user base and community. It is maintained by GitHub (Microsoft).

     

     


    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.

     

     

     

     

  • "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

     

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"


    "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.



    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"


    finally run this application. By this command npm run dev




    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"


    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.

     

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

     



    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)



    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"



    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.


    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"


    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"



    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.



    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"



    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.

     

     

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

     

    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. 

     


    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"





    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.

     

     

  • WHAT WE DO

    We've been developing corporate tailored services for clients for 30 years.

    CONTACT US

    For enquiries you can contact us in several different ways. Contact details are below.

    Hacking Truth.in

    • Street :Road Street 00
    • Person :Person
    • Phone :+045 123 755 755
    • Country :POLAND
    • Email :contact@heaven.com

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.