Created by James Drummond
over 9 years ago
|
||
Basic SetupYou'll need to declare and instantiate objects from various libraries in server.js to get started:var express = require('express'); // call express var app = express(); // define our app using expressvar mongoose = require('mongoose'); // for working w/ our databasevar jwt = require('jsonwebtoken'); // JSON web (authentication) tokensvar superSecret = 'ilovescotchscotchyscotchscotch'; // Secret for the tokenvar bodyParser = require('body-parser'); // get body-parservar morgan = require('morgan'); // used to see requestsvar port = process.env.PORT || 8080; // set the port for our appvar User = require('./app/models/user');// APP CONFIGURATION ---------------------mongoose.connect('mongodb://localhost:27017/users');// use body parser so we can grab information from POST requestsapp.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json());// configure our app to handle CORS requestsapp.use(function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization'); next();});// log all requests to the consoleapp.use(morgan('dev')); Declaring RoutersYou want to group functionality under the url which is being served.// Set up the api router var apiRouter = express.Router();// more routes for our API will happen hereapp.use('/api', apiRouter); // Use the apiRouter for calls to '/api' In Express speak: Mounts the middleware function(s) at the path. So now all calls with /api in the url will be handled by apiRouter. There are various methods defined by Express for authentication that can be used with the router. You can also define route handlers for a subset of paths defined by the parent router.apiRouter.route('/users') // for routes api/users .post( function(){}; ) // handle post requests.get()apiRouter.route('/users/:user_id'); // etc.Declaring useful globals // get the things we need var express = require('express'); var app = express(); var path = require('path'); // set the public folder to serve public assets app.use(express.static(__dirname + '/public'));// Now all assets will be served from the 'public' folder
Express MiddlewareMiddleware is a function with access to the request object (req), the response object (res), and the next middleware in line in the request-response cycle of an Express application, commonly denoted by a variable named next. Middleware can: Execute any code. Make changes to the request and the response objects. End the request-response cycle. Call the next middleware in the stack. An Express application can use the following kinds of middleware: Application-level middleware Router-level middleware Error-handling middleware Built-in middleware Third-party middleware You *mount* the middleware using 'use':app.use(function (req, res, next) { console.log('Time:', Date.now()); next(); });
Inserting Functions as middleware function requiredParamHandler(param){ //do something with a param, e.g., check that it's present in a query string return function (req,res, next) { //use param, e.g., if token is valid proceed with next(); next(); });} app.get('/api/v1/stories/:id', requiredParamHandler('token'), story.show);
Ending requests- res.status(400) is apparently not enough, you need to put res.status(400).end()i.e. you need to send something in addition to res.status
Want to create your own Notes for free with GoConqr? Learn more.