Introdução ao Express.js
Definição
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
- Rápido
- Minimalista
- Flexível
- Não opinativo
- Usado para montar APIs
- Alguns frameworks são baseados no Express
Exemplo de Express.js
hello-simple
├── package.json
├── requests.http
└── src
└── index.js
hello-simple
├── package.json
├── requests.http
└── src
└── index.js
Fluxo da aplicação hello-simple:
Código da aplicação hello-simple:
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');
});
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
{
"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"
}
}
{
"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:
### Get Hello World
GET http://127.0.0.1:3000/
### 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.
node_modules
node_modules
Rotas da Aplicação
Rotas:
/hello/en
=>Hello World!
/hello/pt
=>Olá Mundo!
Estrutura do código:
hello-lang
├── package-lock.json
├── package.json
├── requests.http
└── src
└── index.js
hello-lang
├── package-lock.json
├── package.json
├── requests.http
└── 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');
});
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');
});
### Get Hello World
GET http://127.0.0.1:3000/hello/en
### Get Olá Mundo
GET http://127.0.0.1:3000/hello/pt
### 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
- Route Param
- Body Param
Query Param
Estrutura do código:
bmi-query-param
├── package-lock.json
├── package.json
├── requests.http
└── src
├── bmi.js
└── index.js
bmi-query-param
├── package-lock.json
├── package.json
├── requests.http
└── src
├── bmi.js
└── index.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';
}
}
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';
}
}
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');
});
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');
});
### Get BMI
GET http://127.0.0.1:3000/bmi?weight=100&height=1.5
### Get BMI
GET http://127.0.0.1:3000/bmi?weight=100&height=1.5
Route Param
Estrutura do código:
bmi-route-param
├── package-lock.json
├── package.json
├── requests.http
└── src
├── bmi.js
└── index.js
bmi-route-param
├── package-lock.json
├── package.json
├── requests.http
└── src
├── bmi.js
└── 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');
});
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');
});
### Get BMI
GET http://127.0.0.1:3000/bmi/weight/100/height/1.5
### Get BMI
GET http://127.0.0.1:3000/bmi/weight/100/height/1.5
Body Param
Estrutura do código:
bmi-body-param
├── package-lock.json
├── package.json
├── requests.http
└── src
├── bmi.js
└── index.js
bmi-body-param
├── package-lock.json
├── package.json
├── requests.http
└── src
├── bmi.js
└── 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');
});
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');
});
### Get BMI
POST http://127.0.0.1:3000/bmi
Content-Type: application/json
{
"weight": 100,
"height": 1.5
}
### Get BMI
POST http://127.0.0.1:3000/bmi
Content-Type: application/json
{
"weight": 100,
"height": 1.5
}
Resumo das Rotas
Tipo | Node.js | HTTP | Rota |
---|---|---|---|
Query Param | req.query | GET | /bmi?weight=x&height=y |
Route Param | req.params | GET | /bmi/weight/:weight/height/:height |
Body Param | req.body | POST | /bmi |
Rota | Dados |
---|---|
/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 } |