Advertisement
Guest User

Untitled

a guest
May 31st, 2018
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. const express = require('express');
  2. const app = express();
  3. var http = require('http').Server(app);
  4. app.use(express.static(__dirname + '/'));
  5. var bodyParser = require('body-parser');
  6. app.use(bodyParser.json());
  7. app.use(bodyParser.urlencoded({extended: true}));
  8. const { check, validationResult, body } = require('express-validator/check');
  9. const { matchedData, sanitize } = require('express-validator/filter');
  10.  
  11. //connect to db with knex query builder
  12. var knex = require('knex')({
  13. client: 'pg',
  14. connection: {
  15. host : 'localhost',
  16. user : 'postgres',
  17. password : 'postgres',
  18. database : 'records'
  19. }
  20. });
  21.  
  22. const selectQuery = () => knex('users');
  23.  
  24. app.get('/', (req, res, next) => {
  25. res.sendFile('/views/index.html', {root: __dirname});
  26. })
  27.  
  28. app.get('/data', (req, res) => {
  29. selectQuery().then(data => {
  30. res.json(data);
  31. })
  32. })
  33.  
  34. app.post('/add', [
  35. body(['fname', 'age', 'phone', 'location']).not().isEmpty(),
  36. body('email').isEmail()
  37. ], (req, res) => {
  38. const errors = validationResult(req);
  39. if (!errors.isEmpty()) {
  40. return console.log(errors.mapped());
  41. }
  42. const data = matchedData(req);
  43. console.log(data);
  44. const insertQuery = knex('users').insert([{name: data.fname, age: data.age, phone: data.phone, email: data.email, location: data.location}])
  45. insertQuery.catch(err => console.log(err))
  46. })
  47.  
  48. http.listen(8000, () => console.log("listening on port 8000..."))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement