Introdução ao Express.js

Definição

Site Express:

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Características

Exemplo de Express.js

Open in GitHub Open in Codespaces

Arquivos
hello-simple
├── package.json
├── requests.http
└── src
    └── index.js
Arquivos
hello-simple
├── package.json
├── requests.http
└── src
    └── index.js

Fluxo da aplicação hello-simple:

Código da aplicação hello-simple:

/codes/expressjs/hello-simple/src/index.js
import express from 'express';
 
const app = express();
 
app.get('/', (req, res) => {
  res.send('Hello World!');
});
 
app.listen(3000, () => {
  console.log('App running on port 3000');
});
 
/codes/expressjs/hello-simple/src/index.js
import express from 'express';
 
const app = express();
 
app.get('/', (req, res) => {
  res.send('Hello World!');
});
 
app.listen(3000, () => {
  console.log('App running on port 3000');
});
 

Para a criação do arquivo package.json use este comando no terminal:

$ npm init -y
$ npm init -y

Adição do pacote express.js como dependência do projeto e dos scripts de execução do projeto:

$ npm install express
$ npm install express
/codes/expressjs/hello-simple/package.json
{
  "name": "hello-simple",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "src/index.js",
  "scripts": {
    "start": "node src/index.js",
    "dev": "node --watch src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}
 
/codes/expressjs/hello-simple/package.json
{
  "name": "hello-simple",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "src/index.js",
  "scripts": {
    "start": "node src/index.js",
    "dev": "node --watch src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}
 

Para executar o projeto use algum destes comandos:

$ node src/index.js
$ node src/index.js
$ npm start
$ npm start

Já a execução no modo watch:

$ npm run dev
$ npm run dev

Depende da versão do node.js, o modo watch precisa de um pacoto como o nodemon para funcionar:

 "scripts": {
    ...
    "dev": "nodemon src/index.js"
  },
 "scripts": {
    ...
    "dev": "nodemon src/index.js"
  },
$ npm install nodemon -D
$ npx nodemon src/index.js
$ npm run dev
$ npm install nodemon -D
$ npx nodemon src/index.js
$ npm run dev

Já para testar as requisições use o arquivo requests.http do plugin Rest Client do VSCode:

/codes/expressjs/hello-simple/requests.http
### Get Hello World
 
GET http://127.0.0.1:3000/
 
/codes/expressjs/hello-simple/requests.http
### Get Hello World
 
GET http://127.0.0.1:3000/
 

Cuidado no git para não versionar a pasta node_modules/, use o arquivo .gitignore para desconsiderar a pasta.

/codes/expressjs/hello-simple/.gitignore
node_modules
/codes/expressjs/hello-simple/.gitignore
node_modules

Rotas da Aplicação

Rotas:

Estrutura do código:

Open in GitHub Open in Codespaces

Arquivos
hello-lang
├── package-lock.json
├── package.json
├── requests.http
└── src
    └── index.js
Arquivos
hello-lang
├── package-lock.json
├── package.json
├── requests.http
└── src
    └── index.js
/codes/expressjs/hello-lang/src/index.js
import express from 'express';
 
const app = express();
 
app.get('/hello/pt', (req, res) => {
  res.send('Olá Mundo!');
});
 
app.get('/hello/en', (req, res) => {
  res.send('Hello World!');
});
 
app.listen(3000, () => {
  console.log('App running on port 3000');
});
 
/codes/expressjs/hello-lang/src/index.js
import express from 'express';
 
const app = express();
 
app.get('/hello/pt', (req, res) => {
  res.send('Olá Mundo!');
});
 
app.get('/hello/en', (req, res) => {
  res.send('Hello World!');
});
 
app.listen(3000, () => {
  console.log('App running on port 3000');
});
 
/codes/expressjs/hello-lang/requests.http
### Get Hello World
 
GET http://127.0.0.1:3000/hello/en
 
### Get Olá Mundo
 
GET http://127.0.0.1:3000/hello/pt
 
/codes/expressjs/hello-lang/requests.http
### Get Hello World
 
GET http://127.0.0.1:3000/hello/en
 
### Get Olá Mundo
 
GET http://127.0.0.1:3000/hello/pt
 

Parâmetros de Requisição

Tipos de Parâmetros

Parâmetros:

Query Param

Estrutura do código:

Open in GitHub Open in Codespaces

Arquivos
bmi-query-param
├── package-lock.json
├── package.json
├── requests.http
└── src
    ├── bmi.js
    └── index.js
Arquivos
bmi-query-param
├── package-lock.json
├── package.json
├── requests.http
└── src
    ├── bmi.js
    └── index.js
/codes/expressjs/bmi-query-param/src/bmi.js
export function bmi(weight, height) {
  const bmi = weight / height ** 2;
 
  if (bmi < 18.5) {
    return 'Underweight';
  } else if (bmi < 25) {
    return 'Normal weight';
  } else if (bmi < 30) {
    return 'Overweight';
  } else if (bmi >= 30) {
    return 'Obesity';
  } else {
    return 'Invalid values';
  }
}
 
/codes/expressjs/bmi-query-param/src/bmi.js
export function bmi(weight, height) {
  const bmi = weight / height ** 2;
 
  if (bmi < 18.5) {
    return 'Underweight';
  } else if (bmi < 25) {
    return 'Normal weight';
  } else if (bmi < 30) {
    return 'Overweight';
  } else if (bmi >= 30) {
    return 'Obesity';
  } else {
    return 'Invalid values';
  }
}
 
/codes/expressjs/bmi-query-param/src/index.js
import express from 'express';
import { bmi } from './bmi.js';
 
const app = express();
 
app.get('/bmi', (req, res) => {
  const weight = Number(req.query.weight);
  const height = Number(req.query.height);
 
  const result = {
    weight,
    height,
    bmi: bmi(weight, height),
  };
 
  res.json(result);
});
 
app.listen(3000, () => {
  console.log('App running on port 3000');
});
 
/codes/expressjs/bmi-query-param/src/index.js
import express from 'express';
import { bmi } from './bmi.js';
 
const app = express();
 
app.get('/bmi', (req, res) => {
  const weight = Number(req.query.weight);
  const height = Number(req.query.height);
 
  const result = {
    weight,
    height,
    bmi: bmi(weight, height),
  };
 
  res.json(result);
});
 
app.listen(3000, () => {
  console.log('App running on port 3000');
});
 
/codes/expressjs/bmi-query-param/requests.http
### Get BMI
 
GET http://127.0.0.1:3000/bmi?weight=100&height=1.5
 
/codes/expressjs/bmi-query-param/requests.http
### Get BMI
 
GET http://127.0.0.1:3000/bmi?weight=100&height=1.5
 

Route Param

Estrutura do código:

Open in GitHub Open in Codespaces

Arquivos
bmi-route-param
├── package-lock.json
├── package.json
├── requests.http
└── src
    ├── bmi.js
    └── index.js
Arquivos
bmi-route-param
├── package-lock.json
├── package.json
├── requests.http
└── src
    ├── bmi.js
    └── index.js
/codes/expressjs/bmi-route-param/src/index.js
import express from 'express';
import { bmi } from './bmi.js';
 
const app = express();
 
app.get('/bmi/weight/:weight/height/:height', (req, res) => {
  const weight = Number(req.params.weight);
  const height = Number(req.params.height);
 
  const result = {
    weight,
    height,
    bmi: bmi(weight, height),
  };
 
  res.json(result);
});
 
app.listen(3000, () => {
  console.log('App running on port 3000');
});
 
/codes/expressjs/bmi-route-param/src/index.js
import express from 'express';
import { bmi } from './bmi.js';
 
const app = express();
 
app.get('/bmi/weight/:weight/height/:height', (req, res) => {
  const weight = Number(req.params.weight);
  const height = Number(req.params.height);
 
  const result = {
    weight,
    height,
    bmi: bmi(weight, height),
  };
 
  res.json(result);
});
 
app.listen(3000, () => {
  console.log('App running on port 3000');
});
 
/codes/expressjs/bmi-route-param/requests.http
### Get BMI
 
GET http://127.0.0.1:3000/bmi/weight/100/height/1.5
 
/codes/expressjs/bmi-route-param/requests.http
### Get BMI
 
GET http://127.0.0.1:3000/bmi/weight/100/height/1.5
 

Body Param

Estrutura do código:

Open in GitHub Open in Codespaces

Arquivos
bmi-body-param
├── package-lock.json
├── package.json
├── requests.http
└── src
    ├── bmi.js
    └── index.js
Arquivos
bmi-body-param
├── package-lock.json
├── package.json
├── requests.http
└── src
    ├── bmi.js
    └── index.js
/codes/expressjs/bmi-body-param/src/index.js
import express from 'express';
import { bmi } from './bmi.js';
 
const app = express();
 
app.use(express.json());
 
app.post('/bmi', (req, res) => {
  const { weight, height } = req.body;
 
  const result = {
    weight,
    height,
    bmi: bmi(weight, height),
  };
 
  res.json(result);
});
 
app.listen(3000, () => {
  console.log('App running on port 3000');
});
 
/codes/expressjs/bmi-body-param/src/index.js
import express from 'express';
import { bmi } from './bmi.js';
 
const app = express();
 
app.use(express.json());
 
app.post('/bmi', (req, res) => {
  const { weight, height } = req.body;
 
  const result = {
    weight,
    height,
    bmi: bmi(weight, height),
  };
 
  res.json(result);
});
 
app.listen(3000, () => {
  console.log('App running on port 3000');
});
 
/codes/expressjs/bmi-body-param/requests.http
### Get BMI
 
POST http://127.0.0.1:3000/bmi
Content-Type: application/json
 
{
  "weight": 100,
  "height": 1.5
}
 
/codes/expressjs/bmi-body-param/requests.http
### Get BMI
 
POST http://127.0.0.1:3000/bmi
Content-Type: application/json
 
{
  "weight": 100,
  "height": 1.5
}
 

Resumo das Rotas

TipoNode.jsHTTPRota
Query Paramreq.queryGET/bmi?weight=x&height=y
Route Paramreq.paramsGET/bmi/weight/:weight/height/:height
Body Paramreq.bodyPOST/bmi
RotaDados
/bmi?weight=x&height=y?weight=100&height=1.5
/bmi/weight/:weight/height/:height/bmi/weight/100/height/1.5
/bmi{ "weight": 100, "height": 1.5 }

Referências

Editar esta página