Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by Dan on 2016-08-08.
- */
- var express = require('express');
- var app = express();
- var bodyParser = require('body-parser');
- var mongoose = require('mongoose');
- mongoose.connect('mongodb://localhost:27017/');
- // import user schema
- var User = require('./models/user');
- // parses body of a request so we can use POST properly
- app.use(bodyParser.urlencoded({extended: true}));
- app.use(bodyParser.json());
- // Set the port
- var port = process.env.port || 8080;
- // get instance of the Express router for routes
- var router = express.Router();
- // "middleware" to use for each request
- // validations should happen here to validate requests
- // error handling can also go here
- router.use(function(req, res, next) {
- console.log('Receiving request...');
- next(); // go to next routes, don't stop here (express follows instructions in order from top to bottom, it would stop here without next();)
- });
- // test route to make sure everything is working
- // req = request
- // res = response
- router.get('/test', function(req, res) {
- res.json({message: 'test successful'});
- });
- // on all routes that end with "users", do the following
- router.route('/users')
- .post(function(req, res) {
- var user = new User();
- user.username = req.body.username;
- user.password = req.body.password;
- user.save(function(err) {
- if (err)
- res.send(err);
- res.json({
- message: 'Created user.',
- username: req.body.username,
- password: req.body.password
- });
- });
- });
- // more routes here
- // all routes will be prefixed with /api
- app.use('/api', router);
- app.listen(port);
- console.log('listening on port ' + port);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement