¡GoConqr estrena diseño! Cuéntanos qué te parece.

Apuntes

Express basics

James Drummond Node / Express / Mongo A-Level Inglés 2 páginas

Contenido del apunte (2)

Página 1

Basic Setup

You'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 express

var mongoose = require('mongoose'); // for working w/ our database

var jwt = require('jsonwebtoken'); // JSON web (authentication) tokens

var superSecret = 'ilovescotchscotchyscotchscotch'; // Secret for the token

var bodyParser = require('body-parser'); // get body-parser

var morgan = require('morgan'); // used to see requests

var port = process.env.PORT || 8080; // set the port for our app

var User = require('./app/models/user');

// APP CONFIGURATION ---------------------

mongoose.connect('mongodb://localhost:27017/users');

// use body parser so we can grab information from POST requests

app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

// configure our app to handle CORS requests

app.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 console

app.use(morgan('dev'));

Declaring Routers

You 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 here

app.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 Middleware

Middleware 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);

Página 2

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

Información

Descripción
Basic overview of working with Express for Node
Creado por
James Drummond
Visitas
64
Valoración

Escríbenos

¿Sobre qué es tu mensaje?

¿Qué te parece el nuevo diseño?

¿Te gusta?