Advertisement
Guest User

Untitled

a guest
Aug 11th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Created by Dan on 2016-08-08.
  3.  */
  4.  
  5. var express = require('express');
  6. var app = express();
  7. var bodyParser = require('body-parser');
  8. var mongoose = require('mongoose');
  9. mongoose.connect('mongodb://localhost:27017/');
  10.  
  11. // import user schema
  12. var User = require('./models/user');
  13.  
  14. // parses body of a request so we can use POST properly
  15. app.use(bodyParser.urlencoded({extended: true}));
  16. app.use(bodyParser.json());
  17.  
  18.  
  19. // Set the port
  20. var port = process.env.port || 8080;
  21.  
  22. // get instance of the Express router for routes
  23. var router = express.Router();
  24.  
  25.  
  26. // "middleware" to use for each request
  27. // validations should happen here to validate requests
  28. // error handling can also go here
  29. router.use(function(req, res, next) {
  30.    console.log('Receiving request...');
  31.    next(); // go to next routes, don't stop here (express follows instructions in order from top to bottom, it would stop here without next();)
  32. });
  33.  
  34. // test route to make sure everything is working
  35. // req = request
  36. // res = response
  37. router.get('/test', function(req, res) {
  38.    res.json({message: 'test successful'});
  39. });
  40.  
  41. // on all routes that end with "users", do the following
  42. router.route('/users')
  43.     .post(function(req, res) {
  44.  
  45.        var user = new User();
  46.        user.username = req.body.username;
  47.        user.password = req.body.password;
  48.  
  49.        user.save(function(err) {
  50.           if (err)
  51.              res.send(err);
  52.  
  53.           res.json({
  54.              message: 'Created user.',
  55.              username: req.body.username,
  56.              password: req.body.password
  57.           });
  58.        });
  59.  
  60.     });
  61.  
  62. // more routes here
  63.  
  64. // all routes will be prefixed with /api
  65. app.use('/api', router);
  66.  
  67. app.listen(port);
  68. console.log('listening on port ' + port);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement