Herramientas de usuario

Herramientas del sitio


wiki2:nodejs:express

¡Esta es una revisión vieja del documento!


Express JS

Basic

Installing

  1. Create a packages.json: $ npm init
  2. Install Express and save it in packages: $ npm install express –save

Basic app

var express = require('express');

var app = express();

app.listen(3000, function() {
  console.log("server started on Port 3000");
})

Routes

Take the get to de home (using request and the response):

app.get('/', fucntion(req, res) {
  res.send('Hello world');
});
app.post('/users/add', function(req, res){
  console.log(req.body.firstName);
  res.redirect('/');
});
app.delete('/users/:id', function(req, res) {
  console.log(req.params.id);
});

Things to do with the response

Return a variable in its json format: res.json(person);

Special functions

use is important to put it before any request.

var logger = function (req, res, next){
  console.log('Logging');
  next();
}
app.use(logger);

Set the view engine

app.set('view engine', 'ejs');
// with this we can render views:
res.render('index');

Set the views folder:

app.set('views', path.join(__dirname, 'views');

Set global variables

app.use(function(req, res, next) {
  res.locals.errors = null;
  next();
});

Static path

Add a “public” path:

var path = require('path');
app.use(express.static(path.join(__dirname, 'public'));
wiki2/nodejs/express.1494449540.txt.gz · Última modificación: 2020/05/09 09:24 (editor externo)