Starting server by listen() function in app object
const express = require("express");
const app = express(); // The express() function returns an object (server-side application) that contains various functions used for building a server
console.dir(app); // this is object
const port = 3000; // Port 3000 is the endpoint for the connection between the client and server
app.listen(port); // This starts the server and makes it listen for client requests, although no response is given yet
Responding to the request by the res object
app.use((req,res)=>{
console.log("request received");
let code = "<h1>Fruits</h1> <ul><li>apple</li><li>mango</li>"
res.send(code);
})
The above code displays a html output on the browser
The documentation of response object
Using get() which takes path and callback function as argument
app.get("/",(req,res) => {
res.send("this response is from home page");
});
app.get("/apple",(req,res) => {
res.send("this response is from apple");
});
app.get("/mango",(req,res) => {
res.send("this response is from mango");
});
app.get("*",(req,res) => {
res.send("path not found");
})
The above response is sent when a get request is sent.
There can be any number of paths like ‘/’ is root, /help, /home, /search are some of the paths
The below response is for post request
app.post("/",(req,res)=>{
res.send("this is a post response");
})
Path parameters
app.get("/:username/:password",(req,res) => {
let {username, password} = req.params;
res.send(`this is the username ${username} and your password ${password}`);
});
the url which we send our request contains the username through which the respective account is opened like instagram/apple etc
Query Strings
app.get("/search",(req,res) => {
let {q,color} = req.query; // accessing query strings through req obj
if(!q){
res.send(`<h1>not found</h1>`)
}
res.send(`<h1>the query is ${q} and the color is ${color}</h1>`);
});