Mr_HO1A

NodeJS Server

Sep 16th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Express Js Object Last Main Initilized with ()
  2. const app = require('express')();
  3.  
  4. // Body Parser Only Library Imported
  5. const bodyParser = require('body-parser');
  6.  
  7. // Telling App To Use Body Parser
  8. app.use(bodyParser.json());
  9.  
  10.  
  11. // Note - Every route get or post needs (req,res)
  12. // So it is must to use
  13.  
  14. // Base Url Method Most Basic Method of routing
  15. app.get("/",(req,res)=>{
  16.     res.send("<h1>Hello World!</h1>");
  17. });
  18.  
  19. // URL with URL Embeded Paramerters Method
  20. //  Here name is subblied in URL
  21. // And Can be accessed using req.prams.name
  22. app.get("/greet/:name",(req,res)=>{
  23.     const name = req.params.name;
  24.     res.send("Hello : "+name);
  25. });
  26.  
  27. // Querry Parameters Are Supplied after a ?
  28. // They state not essential data from client
  29. // It can be accessed using req.query.variableName
  30. app.get("/greet2/:name",(req,res)=>{
  31.     const name = req.params.name;
  32.     const surname = req.query.sname;
  33.     res.send("Hello 2 : "+name+" "+surname);
  34. });
  35.  
  36.  
  37. // Just like get post method is there
  38. // Post method is secured and is utilized for
  39. // Login and other confedinital work
  40. // You can access post data using body-parser
  41. // app.body.variableName
  42.  
  43. app.post("/login",(req,res)=>{
  44.  
  45.     console.log(req.body);
  46.  
  47.     const user = req.body.userId;
  48.     const password = req.body.password;
  49.  
  50.     if(password == "1234"){
  51.         res.send("Logged In");
  52.     }
  53.     else{
  54.         res.send("Invalid Username And Password");
  55.     }
  56.  
  57. });
  58.  
  59. // By default if path is called get route always respond first
  60. app.get("/login",(req,res)=>{
  61.     console.log("Login Get Called");
  62.     res.send("Wrong Address");
  63. });
  64.  
  65. // Here we are telling our app object defined in
  66. // Line number 1 to listen or work in which port
  67. // This can be any number in this case 3000
  68. app.listen(3000,()=>{
  69.     console.log("Server Is Running");
  70. }
  71. );
Add Comment
Please, Sign In to add comment