Advertisement
Xzahn

Node JS Routes

Apr 19th, 2020
561
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs')
  2.  
  3. const handleRequest = (req, res) => {
  4.     const url = req.url
  5.     const method = req.method
  6.  
  7.     if (url === '/') {
  8.         res.setHeader('Content-Type', 'text/html')
  9.         res.write('<html><head><title>Home!</title></head>')
  10.         res.write('<body><h1>Welcome Nameless!</h1><form action="/create-user" method="GET"><button>CREATE USER</button></body>')
  11.         res.write('</html>')
  12.         return res.end()
  13.     }
  14.  
  15.     if (url === '/create-user' || method === 'GET') {
  16.         res.statusCode = 200
  17.         res.setHeader('Content-Type', 'text/html')
  18.         res.write('<html><head><title>Home!</title></head>')
  19.         res.write('<body><form action="/users" method="POST"><input type="text" name="username"><button type="submit">LOGIN</button></form></body>')
  20.         res.write('</html>')
  21.         return res.end()
  22.     }
  23.  
  24.     if (url === '/users' && method === 'POST') {
  25.         const requestBody = []
  26.  
  27.         req.on('data', chunk => {
  28.             requestBody.push(chunk)
  29.         })
  30.        
  31.         return req.on('end', () => {
  32.             const parsedBody = Buffer.concat(requestBody).toString()
  33.             const username = parsedBody.split('=')[1]
  34.  
  35.             res.statusCode = 200
  36.             res.setHeader('Content-Type', 'text/html')
  37.             res.write('<html><head><title>Home!</title></head>')
  38.             res.write(`<body><h1>Welcome, ${username}!</h1></body>`)
  39.             res.write('</html>')
  40.             return res.end()
  41.         })
  42.     }
  43.  
  44.     res.statusCode = 302
  45.     res.setHeader('Location', '/')
  46.     res.end()
  47. }
  48.  
  49. module.exports = handleRequest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement