BackEnd for WebDev

 ye blog hinglish me likha gaya hai...jo samjh aaya uska bss notes hai


BackEnd wali javascript:

1. Download NodeJs: 

what is NodeJs;----

browser V8 engine,  Node.js is a runtime that lets you run JavaScript on a server to build fast and scalable web applications.  JavaScript talk directly to databases, files, and networks without needing a web browser.

write this in terminal:

npm init   [press enter] -->you can give project name, author etc,..to skip adding detail write {npm init -y}

after this current folder.. becomes npm project, we can install packages..it becomes single entity,..

module/package -->borrowed code, written by someone else,..we are just importing to use it

when you install any package,.. node_modules package appear in folder which holds packages and dependencies, helps to manage packages,...if node_modules  get deleted  "no worries"  dependencies are stored in package,json just write in terminal   [npm install]............///node_modules of complex project has toooooo much code

 node --version (tells the version of nodeJS)

npm --version(tells the version of npm)          {node package manager}


MAKE  NEW FILE    myserver.js   IN SAME DIRECTRARY:

paste the following content:

const http = require('node:http');

const hostname = '127.0.0.1';
const port = 3000;


const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/html');
  res.end('<h1>Hello World<\h1>');
});


server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});


run the code you'll get in terminal

server running at http://127.0.0.1:3000/ (3000 is port)

paste the link on browser you'll see Hello World

___________________________________________________________________________________


ECMAScript ES6     v/s     CommonJS


to keep restarting the server, whenever you make changes in the file:--- write in terminal

npm install --global nodemon   (installs for whole PC not just the npm directrary)

To start this extension:    nodemon main.js   

const server = http.createServer((req, res) => {            
    res.statusCode = 200;                                      
    res.setHeader('Content-Type', 'text/html');                
    res.end('<h1>Hello World<\h1>');                          
  });      

"content type" is by default 'text/plain'.....to render html in res.end we changed it to
'text/html'


'require' is used to import module, this method is CommmonJs
Now go to package.json
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",

below main, write "type":"module" //by default it is commonJS
type equal to module is for ECMAScript ES6 relatively newer syntax with new features

in ES6 modules are loaded asynchronously whereas in 'require' it loads synchronously(blocking code)

const http = require('node:http');

after changing to 'type':'module' require will not work,...
change the above line by

import http from "http"


exporting any function or constant in ECMAScript:

let one file: myModuleExport.js
export const a=3;
export const b=5;
export const c=1;

let obj;
export default obj={
    x:5,
    y:10
}

another file: myModuleImport.js
import {a,c} from "./myModuleExport.js"    //named import
console.log(a,c);

import object from "./myModuleExport.js" /default import (give any name TO obj)
console.log(object)


exporting any function or constant in CommonJS:

export file:
module.exports={
    a:4,
    b:9
}

let c=56;
module.exports=c;

import file:
const a=require("./modExportREQ.js")
console.log(a)


we can use this module in browser too...

    <script type="module" src="myModuleExp.js"></script>


______________________________________________________________________________________

Working with Files: fs and path modules

const fs=require("fs")

console.log("starting")

fs.writeFileSync("nikhil.txt","i am nikhil")   //blocks the thread

fs.writeFile("nik.txt","nikhil is good",()=>{   //runs asynchronously
    console.log("written")
    fs.readFile("nikhil.txt",(error,data)=>{ //if we keep doing this, it'll make callback hell
        console.log(error, data.toString())
    })
})

console.log("ending")



************************************************************************************

express:

Express.js simplifies Node.js web development by providing a fast, minimal, and flexible framework for handling routes, middleware, and APIs efficiently. 🚀

const express=require('express')
const app=express()
const port=3000

//app.get or app.post or app.put or app.delete
app.get('/',(req,res)=>{
    res.send('Hello, World!')
})

app.get('/about',(req,res)=>{
    res.send('about the web page')
})

app.get('/conatct',(req,res)=>{
    res.send('contact us')
})

app.get('/blog',(req,res)=>{
    res.send('read blog about the page')
})

app.get('/blog/:slug',(req,res)=>{  //slug is variable name

    //logic to fetch {slug} from the db
    res.send(`read blog about the page inside ${req.params.slug}`)

    //for url: http://localhost:3000/blog/nikhil-loves-rakhi?mode=dark&region=in
    console.log(req.params) //will output { slug:'nikhil-loves-rakhi'}
    console.log(req.query)  //will output { mode: 'dark',region : 'in'}
})

app.listen(port,()=>{
    console.log(`example app listening on port ${port}`)
})

//app.use(express.static('public'))

//whenever we write on browser:  127.0.0.1:3000   its a 'get' request



*************************************************************************************

Response, Request and Router


const express=require('express')
const app=express()
const port=3000

app.use(express.static("public")) //files inside 'public' folder can be accessed, in browser

app.get('/',(req,res)=>{
    console.log("hey its a get request")
    res.send('Hello World again!')
})

app.post('/',(req,res)=>{
    console.log("hey its a post request")
    res.send('Hellow world to post request')
})

app.put('/',(req,res)=>{
    console.log("hey its a put request")
    res.send('Hellow world to put request')
})

app.get("/index",(req,res)=>{
    console.log("trying to render HTML page")
    res.sendFile('templates/index.html',{root:__dirname})
})


app.listen(port,()=>{
    console.log(`example app listening on port ${port}`)
})


html file inside 'public' folder(for post request)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>testing post request</title>
</head>
<body>
    <script>
        async function testPost(){
            let a=await fetch("/", {method:"POST"})
            let b=await a.text();
            console.log(b)
        }

        testPost()
    </script>
</body>
</html>


index.html file written inside templates folder, "accessing through 'get' request"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>hello world checking 1 2 3...</h1>
</body>
</html>





Routes: make folder named 'routes'...for eg. if we are making webpage where we'll have too many end point
like about, contact, comment etc. if written inside one file it'll create clutter,..so we route it through another file


inside main.js
const blog=require('./routes/blog')
app.use('/blog',blog)


inside "/routes/blog.js"
const express=require('express')
const router=express.Router()

//define the homepage route
router.get('/',(req,res)=>{
    res.send("blogs home page")
})

//define about the blog
router.get('/about',(req,res)=>{
    res.send('about blog')
})

//define the about the route
router.get('/blogpost/:slug',(req,res)=>{
    res.send(`fetch the blogpost for ${req.params.slug}`)
})




















Comments

Popular posts from this blog

Decorators in Pythons | easy way to learn about decorators

Useful Git Commands for Windows

Strings in python: Methods, Operations, and Reversing