-->

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.

  • How setTimeout Uses Closures with var and let

     

    How setTimeout Uses Closures with var and let

     

     How setTimeout Uses Closures with var and let 


     
    This blog we have seen javascript  closure wtih setTimeout and  solve let and var issue wtih forloop basic and how is it work, we have already seen some Javscript,  mongodb basic, CRUD operation, connect mongodb with nodejs, read, update, delete, POST, GET API etc. we should not face any problem while making Database, collection(table) and using the data in nodejs even whenever we will make API. Read data from mongodb in nodejs



    • # What is Closure with setTimeout
    • # Solve for loop issue wtih let and var using closure concept

     

     

    What is Closure ?

     

    A closure is created when a function remember its lexical scope even when its executed outside the scope. In other terms we can say that a closure give a function access to variable from its surrounding environment. 

     

     

    Don't worry i will give you an example - Suppose that you have a backpack with your notes, pens and books etc. You leave the classroom (your outer function), but you still have access to everything in your backpack (your closures). Whenever you need to solve a problem later, you can pull out the knowledge you saved in your backpack.

     

     

    function makeAdder(x) {
      return function(y) {
        return x + y;
      };
    }
    
    const add5 = makeAdder(5);
    const add10 = makeAdder(10);
    
    console.log(add5(2)); // 7
    console.log(add10(2)); // 12
    

     

     

    Here in this code makeAdder function takes a single argument x and return a new function.

    The return function takes a single argument  and return the sum of x and y.

    add5 and add10 are closures that maintain their own separate lexical environment , holding the value of x from when they were created 

     

     

    Example : A Basic Closure

     

     

    function outerfunction() {
       const outerVariable = 'Hello, Atul';
    
    
       function innerFunction() {
         console.log(outerVariable);
       }
    
       return innerFunction() {
    }
    
    const myClosure = outerFunction();
    myClosure();        //output: 'Hello, Atul'
    
    
    
    

     


    What's Happening Here?

    # innerFunction is returned from outerFunction.

    # Even though outerFunction has finished executing, innerFunction still remembers outerVariable.

    # A function is defined inside another function.

    # The inner function "remembers" the variables of the outer function.



    How setTimeout Uses Closures:

     # Inner Function: When you pass a function to setTimeout, that function forms a closure. It "remembers" the variables and values from the scope where it was created.
     

    # Delayed Execution: setTimeout schedules the function to be executed after a specified delay. But even after the surrounding code has finished running, the inner function (callback) still has access to its original scope's variables.

     

     

    for(var i=0; i< 10; i++)
    {
        setTimeout(function(){
            console.log(i)
        })
    }
    
    

     

     

    in this code why always showing output 10, 10, 10...

    The reason the code logs 10 repeatedly is due to how closures work in JavaScript. When the setTimeout callback executes, it accesses the value of i from the surrounding scope (the loop). By the time the callbacks execute, the loop has already finished, and i is equal to 10 for all of them. 

     

     

    How setTimeout Uses Closures with var and let

     

     

     


    Explanation:

     

    # The var keyword declares i in the function scope (or global scope if not inside a function). This means all iterations of the loop share the same i variable.

    # The setTimeout function schedules the callback to execute after a certain delay, but the loop doesn't wait for the callbacks to execute—it continues running to completion.

    # By the time the callbacks from setTimeout are executed, the loop has already completed, and the value of i has reached 10.

     

     Fix: Using let


    The easiest way to fix this issue is to use the let keyword instead of var. Variables declared with let have block scope, so each iteration of the loop gets its own copy of i.

     A function is defined inside another function.

    The inner function "remembers" the variables of the outer function.

     

    for (let i = 0; i < 10; i++) {
        setTimeout(function () {
            console.log(i);
        }, 0);
    }
    
    
    

     

     

    Here, each i is scoped to its specific iteration, so the output will correctly log 0, 1, 2, ..., 9.

     

     

     

    How setTimeout Uses Closures with var and let

     

    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.

     

     


  • Breaking It Down JWT Authentication

     

    Breaking It Down JWT Authentication

     

     Breaking It Down JWT Authentication

     

    JWT (JSON web token) authentication is a widely used method for securely transmitting information between parties as a JSON object. It is a token-based approach often employed in web applications for authentication and authorization purposes. 

     

    How JWT Works

     

    1) Token creation: When a user logs in or registers, the server creates a token (JWT) that contains encoded information (claims) such as user ID or roles. This token is signed (often using  a secret key or a public/private key) to ensure its integrity.

     

     2) Token Structure: A JWT consists of three parts:

     

    i) Header: Contains information about the token type (JWT) and the signing algorithm (eg: HMAC SHA256).

    ii) Payload: Contains the claims (user data and metadata)

    iii) Signature: Created using the header, payload, and a secret key.

     

     

     Benefits of JWT for Registration Authentication

     

    i) Stateless: JWTs enable stateless authentication, meaning the server doesn't need to store user session data. All information is encoded in the token, making it lightweight and scalable.

    ii) Security: JWTs are signed, so can't be tempered and without invalidating the signature.

    iii) Easy to Use: JWTs are easy to create and vaidate, making them ideal for handling user registration, email verification, OTP verification and more.

     

     

    Breaking it Down

     

     

     

    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkF0dWwgS3VtYXIiLCJlbWFpbCI6Imt1bWFyYXR1bGphaXN3YWwyMjJAZ21haWwuY29tIiwiaWF0IjoxNTE2MjM5MDIyfQ.YOdnmqIgD7L2PU0xHpGVzL_-tgiktaWk17hAIm__bC0
    

     

     

     A JWT (JSON web token) is a base64-encoded string that consists of three parts. Header, Payload, and signature, separated by dots (.) . Here's an example of what a JWT look like after a user registers:


    1] Header: Encoded metadata about the token



    {
      "alg": "HS256",
      "typ": "JWT"
    }
    



    alg: Algorithm used for signing (Eg. HS256 for HMAC SHA-256).

    typ: Token type (always JWT)


    Encoded as Base64:


    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
    



    2] Payload: Contains claims or user-related data.



    {
      "sub": "1234567890",
      "name": "Atul Kumar",
      "email": "kumaratuljaiswal222@gmail.com",
      "iat": 1516239022
    }
    



    userId: A unique identifier for the user (Eg: database ID)

    name: User's name

    email: User's email address

    iat: Issued At Time (UNIX timestamp of when the token was created)


    Encoded as Base64:

     

     

    eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkF0dWwgS3VtYXIiLCJlbWFpbCI6Imt1bWFyYXR1bGphaXN3YWwyMjJAZ21haWwuY29tIiwiaWF0IjoxNTE2MjM5MDIyfQ
    

     

     

    3] Signature: Ensures the token's integrity, Created using the encoded header, encoded payload, and a secret key (eg: mysecretkey).

     

     


    HMACSHA256(
      base64UrlEncode(header) + "." +
      base64UrlEncode(payload),
      secret
    )
    
    


     The result:


     

    YOdnmqIgD7L2PU0xHpGVzL_-tgiktaWk17hAIm__bC0
    

     

     

     Full JWT Structure:


    [Header].[Payload].[Signature]

     

     

    JWT Auth Code  


    Link - https://github.com/whoiskumaratul/jwt-authentication.git

     


    Notes:



    Readable Information: The Header and Payload are Base64-encoded and can be decoded to see the content. This is why sensitive data (e.g., passwords) should never be included in a JWT.

    Signature Security: The Signature ensures the token hasn't been tampered with. Without the secret key, an attacker cannot forge a valid token.

    Expiration:
    Typically, JWTs also include an expiration (exp) claim to ensure the token is valid only for a certain time frame.

    Adding an expiration claim example to the payload:

     

     

    {
      "sub": "1234567890",
      "name": "Atul Kumar",
      "email": "kumaratuljaiswal222@gmail.com",
      "iat": 1516239022
      "exp": 1689692100
    }
    
    

     

     

     This JWT would expire in 1 hour (if iat is 1516239022 and exp is 1689692100).

     

     

     


     

    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.

     

     

  • Submit a new Singapore Tax Form for adsense

     

    Submit a new Singapore Tax Form for adsense

     

     

    Submitting a new Singapore Tax Form for AdSense involves updating your tax information in your Google AdSense account to comply with Singapore tax regulations. Here’s a step-by-step guide on how to do it:



    ### Step-by-Step Guide to Submit a New Singapore Tax Form for Google AdSense:

    1. **Log in to Your AdSense Account**  
       - Go to [Google AdSense](https://www.google.com/adsense/) and log in using your account credentials.

     

     

    Submit a new Singapore Tax Form for adsense

     

     



    2. **Access the Payments Section**  
       - Once logged in, click on the **Payments** tab in the left-hand menu.
       - In the Payments section, look for **Manage settings**  and click on it.

     

     

    Submit a new Singapore Tax Form for adsense

     

     



    3. **Navigate to the Tax Information Section**  
       - Scroll down to the **Payments profile** section, where you’ll find an option for **United States tax info**.
       - Click on **Manage tax info** to proceed.

     



    4. **Update or Add New Tax Information**  
       - You will see your existing tax documents if you have any. To add a new tax form, click on the **Add tax info** button.
       - You’ll be asked to re-authenticate with your Google account password.

     

     

    Submit a new Singapore Tax Form for adsense

     



    5. **Choose the Appropriate Tax Form**  
       - Google AdSense will guide you to select the appropriate tax form based on your account type (individual or business).
     


    Submit a new Singapore Tax Form for adsense



    Submit a new Singapore Tax Form for adsense


     
     

    Submit a new Singapore Tax Form for adsense



     

    As a bussiness type choose and establishment in singapore simply select NO option.



    Submit a new Singapore Tax Form for adsense





    6. **Provide Your Tax Details**  
       - Sinapore Goods and Services Tax (GST) click for this  NO.
       - leave UEN number as a blank 
       - Tax exemtpions  : you are eligible and click on YES option.



    Submit a new Singapore Tax Form for adsense



    7. **Tax Residency**  
       - Region/country : choose your country .
       - Proof of tax residency - For this first you need to select Other document and then upload your Pan Card or Aadhaar card.   
     

     

     

    Submit a new Singapore Tax Form for adsense

     

    8. **Expiry Date**  
       - You better know there is no expiry date for aadhaar card or pan card.
     

     

    Submit a new Singapore Tax Form for adsense

     

     

     


    9. **Certify and Submit the Form**  
       - Review the information you’ve provided, then check the certification box to confirm that the details are accurate.
       - Click on **Submit** to complete the process.

     

     

    Submit a new Singapore Tax Form for adsense

     


    10. **Confirmation and Review**  
       - Once submitted, you’ll receive a confirmation email from Google AdSense regarding the tax information submission.
       - Your payment may be subject to tax withholding based on the information you provided.



    after 12-24 hours I got the mail....







    By following these steps, you can successfully submit or update your Singapore Tax Form for Google AdSense and ensure that your account is compliant with tax regulations.

     

     

     Disclaimer



    The information provided on this blog is for general informational purposes only and is not intended to be a substitute for professional tax advice. While we strive to ensure the accuracy and completeness of the information presented, we make no guarantees regarding its accuracy, applicability, or completeness.

    Tax regulations and procedures may vary based on your individual circumstances and may change over time. It is strongly recommended to consult with a qualified tax professional or refer directly to official government sources for specific guidance related to submitting a Singapore Tax Form for Google AdSense.

    By using this information, you acknowledge that you are doing so at your own risk, and the blog owner shall not be held liable for any errors, omissions, or any loss or damage arising from the use of the information provided.

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

     

     

  • Events and Event Emitter in nodejs

     

    Events and Event Emitter in nodejs

     

     

    Events and Event Emitter in nodejs



    This blog we have seen mongodb basic and how is it work with installation and after installation, we have already seen mongodb basic, CRUD operation, connect mongodb with nodejs, read, update, delete, POST, GET API etc. we should not face any problem while making Database, collection(table) and using the data in nodejs even whenever we will make API. Read data from mongodb in nodejs



    • # What is Mongoose
    • # Install Mongoose
    • # What is Events and Event Emitter
    • # Make an event and call it


     

    Now in this blog  we will use mongoose. There is an npm package to connect nodes to mongodb. Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. They created mongoose by improving mongodb, with the help of which you can create schemas and models of mongoose's movements.

    Suppose that there are 4 fields in our database (like name, brand, price, category) and the user wants to add a 5th field also (like color) but we want to add only 4 fields, for this we create schemas.

    Here you can also define TYPE in schemas like price type is numeric but if any user wants to use quotes (" " ' ') then we can stop the user for this.

    in sort we can apply validation in mongoose but we can't in directly mongodb.

     

     

     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.




    Install Mongoose


    For this you need to copy this (npm i mongoose) and paste it in project's terminal.

    https://www.npmjs.com/package/mongoose

     

     

     

    Events and Event Emitter in nodejs

     

     

    What is Events and Event Emitter

     

    In nodejs, an event is an action or occurrence that can be observed and responded to . Node.js provides the event emitter pattern as a core module to handle events. The Event emitter is an implementation of the observer pattern allowing objects (event emitter) to emit the named events that cause function objects (listeners) to be called.

     

    OR

     

    if i will use button in HTML and add the onClick event and whenever we click on button and generate the function and get a signal that please call the function and execute the code.

    and the event is that which observes the singal received from the event and works on that pattern.



    Basic Usage:



    To use the Event Emitter, you first create an instance of Event Emitter.

    You can then use the .on(eventName, listener) method to attach a listener function to a specific event.

    The .emit(eventName, ...args) method is used to emit (trigger) an event, and any attached listeners for that event are called.

     

     

    Q) How can we make a button in Node.js ?

     Ans - Through API and use Event Emitter

     

     

    Make an event and call it

     

    First we will make a API and import express and EventEmitter (EventEmitter is inbuilt module in nodejs) so don't need to install in nodejs.



    const express = require('express')
    const EventEmitter = require('events');
    const app = express()
    
    
    app.get("/", (req, resp) => {
        resp.send("Done")
        console.log("API called")
    })
    
    app.listen(8000)
    

     

     

    Events and Event Emitter in nodejs

     

     

    Now we will see when we create so many API then we will check how many hit on particular API.


     

    app.get("/", (req, resp) => {
        resp.send("Home page API")
        console.log("Home page API called")
    })
    
    
    app.get("/search", (req, resp) => {
        resp.send("Search API")
        console.log("Search API called")
    })
    
    
    
    app.get("/update", (req, resp) => {
        resp.send("update page API")
        console.log("update API called")
    })
    
    

     

     

     Now we make a function that means it will keep updating the count of every hit we get on our API in the database.



    const express = require("express");
    const EventEmitter = require("events");
    const app = express();
    
    const event = new EventEmitter();
    //this is object
    
    let count = 0;
    
    event.on("countAPI", () => {
      count++;
      console.log("Event called", count);
    });
    
    //first is the event name - countAPI
    //second is the callback function
    
    
    
    app.get("/", (req, resp) => {
      resp.send("Home page API");
      event.emit("countAPI"); 
    });
    
    app.get("/search", (req, resp) => {
      resp.send("Search API");
      event.emit("countAPI"); 
    });
     
    app.get("/update", (req, resp) => {
      resp.send("update page API");
      event.emit("countAPI");
    });
    
    app.listen(8000);
    
    

     

     

     

    Events and Event Emitter in nodejs

     

     


    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.

     

     

  • OS module in Nodejs

     

    OS module in Nodejs

     

     

     

    upload the file from nodejs



    This blog we have seen mongodb basic and how is it work with installation and after installation, we have already seen mongodb basic, CRUD operation, connect mongodb with nodejs, read, update, delete, POST, GET API etc. we should not face any problem while making Database, collection(table) and using the data in nodejs even whenever we will make API. Read data from mongodb in nodejs



    • # What is OS module
    • # Important functions of OS module

     

    What is OS Module ?

     

    In Node.js, the 'os' (operating system) module provides a set of methods to interact with the operating system. It allows you to access information about the system's resources, network interfaces, and other related details. Here are some commonly used functionalities provided by the OS module.

     

     

    const os = require("os");
    console.log(os.arch())
    
    

     

    Returns a string identifying the operating system CPU architecture (e.g., 'x64').


     

    OS module in Nodejs

     

     

    const os = require("os");
    console.log(os.freemem()/(1024*1024));
    console.log(os.freemem()/(1024*1024*1024));
    
    

     

    Returns the amount of free system memory in bytes. 


     

    OS module in Nodejs

     

     

     

    const os = require("os");
    
    console.log(os.totalmem()/(1024*1024));
    console.log(os.totalmem()/(1024*1024*1024));
    
    

     

    Returns the total amount of system memory in bytes.

     

     

    OS module in Nodejs

     

     

    const os = require("os");
    
    console.log(os.hostname());
    
    

     

    Returns the host name of the operating system.

     

    OS module in Nodejs

     

     

    const os = require("os");
    
    console.log(os.platform());
    
    

     

     

    Returns a string identifying the operating system platform (e.g., 'darwin', 'win32', 'linux').

     

     

    OS module in Nodejs

     

     

    const os = require("os");
    
    console.log(os.userInfo());
    

     


     

    OS module in Nodejs

     

     


    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.