-
Notifications
You must be signed in to change notification settings - Fork 2
Backend
Wellington Silva edited this page Mar 30, 2020
·
1 revision
mkdir backend
cd backend
npm init -y # incializando node.js
npm install express # instalando micro-framework 'express' (configura rota e interpreta parâmetros)
touch index.js
-
request
: guarda todos os dados que são fornecidos da requisição do usuário -
response
: responder todos os dados que são requisitados pelo usuário
const express = require('express');
const app = express();
app.get('/',(request, response) => {
return response.send('Hello World');
});
app.listen(3333);
node index.js # ativa o localhost:3333
-
GET
: Buscar/Listar uma informação do back-end -
POST
: Cria uma informação do back-end -
PUT
: Altera uma informação do back-end -
DELETE
: Delete uma informação do back-end
Insomnia.rest : (Ferramenta para manipular os Métodos HTTP)
$ sudo snap install insomnia
Client Code
var data = JSON.stringify({
"id": "aa1e8513"
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://localhost:3333/sessions");
xhr.setRequestHeader("authorization", "aa1e8513");
xhr.setRequestHeader("content-type", "application/json");
xhr.send(data);
POST /sessions HTTP/1.1
Authorization: aa1e8513
Content-Type: application/json
Host: localhost:3333
Content-Length: 22
{
"id" : "aa1e8513"
}
Curl
curl --request POST \
--url http://localhost:3333/sessions \
--header 'authorization: aa1e8513' \
--header 'content-type: application/json' \
--data '{
"id" : "aa1e8513"
}'
Client Code
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "http://localhost:3333/profile");
xhr.setRequestHeader("authorization", "aa1e8513");
xhr.send(data);
GET /profile HTTP/1.1
Authorization: aa1e8513
Host: localhost:3333
Curl
curl --request GET \
--url http://localhost:3333/profile \
--header 'authorization: aa1e8513'
- List
Client Code
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "http://localhost:3333/incidents?page=1");
xhr.setRequestHeader("authorization", "aa1e8513");
xhr.send(data);
GET /incidents?page=1 HTTP/1.1
Authorization: aa1e8513
Host: localhost:3333
Curl
curl --request GET \
--url 'http://localhost:3333/incidents?page=1' \
--header 'authorization: aa1e8513'
- Create
Client Code
var data = JSON.stringify({
"title": "Casos 1",
"description": "Detalhes dos casos",
"value": 120
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://localhost:3333/incidents");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("authorization", "aa1e8513");
xhr.send(data);
POST /incidents HTTP/1.1
Content-Type: application/json
Authorization: aa1e8513
Host: localhost:3333
Content-Length: 89
{
"title" : "Casos 1",
"description" : "Detalhes dos casos",
"value" : 120
}
Curl
curl --request POST \
--url http://localhost:3333/incidents \
--header 'authorization: aa1e8513' \
--header 'content-type: application/json' \
--data '{
"title" : "Casos 1",
"description" : "Detalhes dos casos",
"value" : 120
}'
- Delete
Client Code
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("DELETE", "http://localhost:3333/incidents/3");
xhr.setRequestHeader("authorization", "aa1e8513");
xhr.send(data);
DELETE /incidents/3 HTTP/1.1
Authorization: aa1e8513
Host: localhost:3333
Curl
curl --request DELETE \
--url http://localhost:3333/incidents/3 \
--header 'authorization: aa1e8513'
- List
Client Code
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "http://localhost:3333/ongs");
xhr.send(data);
GET /ongs HTTP/1.1
Host: localhost:3333
Curl
curl --request GET \
--url http://localhost:3333/ongs
- Create
Client Code
var data = JSON.stringify({
"name": "APAD2",
"email": "contato@apad.com.br",
"whatsapp": "470000000",
"city": "Rio do Sul",
"uf": "SC"
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://localhost:3333/ongs");
xhr.setRequestHeader("content-type", "application/json");
xhr.send(data);
POST /ongs HTTP/1.1
Content-Type: application/json
Host: localhost:3333
Content-Length: 131
{
"name" : "APAD2",
"email" : "contato@apad.com.br",
"whatsapp" : "470000000",
"city" : "Rio do Sul",
"uf" : "SC"
}
Curl
curl --request POST \
--url http://localhost:3333/ongs \
--header 'content-type: application/json' \
--data '{
"name" : "APAD2",
"email" : "contato@apad.com.br",
"whatsapp" : "470000000",
"city" : "Rio do Sul",
"uf" : "SC"
}'
-
Query Params
: parâmetros nomeados enviados na rota após "?". Exemplo: filtro, páginação; -
Route Params
: parâmetros utilizados para identificar recursos ; -
Request Body
: Corpo da requisição, utilizado para criar ou alterar recursos.- Converter json para javascript:
app.use(express.json());
.
- Converter json para javascript:
- ONG
- Cadastrar
- Login
- Logout
- Contato
- CASOS (incident)
- Cadastrar
- Deletar
- Listar
- Especificos
- Todos
- Driver: SELECT * FROM users
- Query Builder: table('users').select( * ).where()
Install
npm install knex
npm install sqlite3
npx knex init # configura o acesso ao banco de dados para cada aplicação
- Configuração do database pelo
knex
// knexfile.js
development: {
client: 'sqlite3',
connection: {
filename: './src/database/db.sqlite'
},
migrations: {
directory: './src/database/migrations'
},
useNullAsDefault: true
},
- gera uma tabela apenas no knexfile
create schema
npx knex migrate:make create_ongs
- configura a estrutura da tabela para o comando
create table
// 20200325083011_create_ongs.js
exports.up = function(knex) {
return knex.schema.createTable('ong', function (table) {
table.string('id').primary();
table.string('name').notNullable();
table.string('email').notNullable();
table.string('whatsapp').notNullable();
table.string('city').notNullable();
table.string('uf',2).notNullable();
})
};
exports.down = function(knex) { return knex.schema.dropTable('ongs'); };
- executa o comando
create table
e cria tabela no banco de dados
npx knex migrate:latest
- Desfaz o último comando do
npx knex migrate:latest
npx knex migrate:rollback
Define quem possui autoridade de acessar a aplicação
npm install cors
Exemplo de uso:
app.use(cors({
origin: 'domínio_da_app.com'
}));