Advertisement
Guest User

Untitled

a guest
Jan 27th, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var express = require('express');
  2. var bodyParser = require('body-parser');
  3. var app = express();
  4.  
  5. app.use(bodyParser.urlencoded({ extended: false }));
  6. app.use(bodyParser.json());
  7.  
  8. app.set('view engine', 'pug');
  9. app.set('views', './');
  10.  
  11. app.get('/hello', function (req, res) {
  12.    res.send('Hello World!');
  13. })
  14.  
  15. app.get('/form', function (req, res) {
  16.    var htmlFields =  '<body><form method="post" action="/formdata"><table >'+
  17.                         '<tr><td><label for="username">Username:</label></td><td><input type="text" id="username" name="username"></td></tr>'+
  18.                         '<tr><td><label for="password">Password:</label></td><td><input type="password" id="password" name="password"></td></tr>'+
  19.                         '<tr><td><label for="email">Email:</label></td><td><input type="email" id="email" name="email"></td></tr>'+
  20.                         '<tr><td><input type="submit"></td></tr></table>'+
  21.                      '</form></body>';
  22.    res.send(htmlFields);
  23. })
  24.  
  25. app.post('/formdata', function(req, res, next) {
  26.     res.render('index', { title: 'Result', username: 'Hello '+req.body.username, password: 'Your password is '+req.body.password, email:
  27.        'Your email is '+req.body.email
  28.     });
  29. });
  30.  
  31. app.get('/jsondata', function (req, res) {
  32.     if (!req.query.json) {
  33.         return res.send('required query json with valid json');
  34.     }
  35.    
  36.     let body;
  37.     try {
  38.         body = JSON.parse(req.query.json);
  39.     }
  40.     catch (_a) {
  41.         return res.send('invalid json');
  42.     }
  43.    
  44.     var error='';
  45.     if (!body.username) {
  46.         error+='username not found in json</br>';
  47.     }
  48.     if (!body.password) {
  49.         error+='password not found in json</br>';
  50.     }
  51.     if (!body.email) {
  52.         error+='email not found in json</br>';
  53.     }
  54.    
  55.     if (error.length>0)
  56.     {
  57.        return res.send(error);
  58.     }
  59.    
  60.     return res.render('index', { title: 'Result', username: 'Hello '+body.username, password: 'Your password is '+body.password, email:
  61.        'Your email is '+body.email
  62.     });
  63. });
  64.  
  65. var server = app.listen(8080, function () {
  66.    var host = server.address().address
  67.    var port = server.address().port
  68.    
  69.    console.log("Example app listening at http://%s:%s", host, port)
  70. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement