DEV Community

Jessé
Jessé

Posted on

Nodejs: Express, Nodemon, Rotas e HTTP Requests

Como criar um servidor com Express
Arquivo dedicado às rotas
Métodos HTTP
Parâmetros de Requisição
Middleware

Como criar um servidor com Express:

const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
//Converte para json
app.use(express.json());
//Ouvir a porta
app.listen(3333);
view raw index.js hosted with ❤ by GitHub

Arquivo dedicado às rotas:

const express = require('express');
const { uuid, isUuid } = require('uuidv4');
const projects = [];
const app = express();
app.use(express.json());
app.get('/projects', (request, response) => {
console.log(3);
const { title, owner } = request.query;
const results = title ? projects.filter(project => project.title.includes(title)) : projects;
return response.json(results);
});
app.post('/projects', (request, response) => {
const { title, owner } = request.body;
const project = { id: uuid(), title, owner };
projects.push(project);
return response.json(project);
});
app.put('/projects/:id', (request, response) => {
const { id } = request.params;
let projectIndex = projects.findIndex( project => project.id === id );
if ( projectIndex < 0 ) return response.status(400).json({ error: 'Project not found.' });
const project = {
id,
title,
owner
};
projects[projectIndex] = project;
return response.json(project);
});
app.delete('/projects/:id', (request, response) => {
const { id } = request.params;
let projectIndex = projects.findIndex( project => project.id === id );
if ( projectIndex < 0 ) return response.status(400).json({ error: 'Can not delete.' });
projects.splice(projectIndex, 1);
return response.send();
});
app.listen(3333, () => {
console.log('back-end started! 🚀');
});
view raw index.js hosted with ❤ by GitHub

Métodos HTTP:
São métodos utilizados para trafegar dados.

  • GET: Buscar informações no back-end
  • POST: Criar informações no back-end
  • PUT: Alterar informações no back-end
  • PATCH: Alterar informações no back-end
  • DELETE: Deletar informações no back-end

Parâmetros de Requisição:
São parâmetros enviados em requisições HTTP

  • Query Params: Filtros e paginação
  • Route Params: Identificar recursos (Atualizar/Deletar)
  • Request Body: Conteúdo na hora de criar ou editar um recurso (JSON)

Middleware:
Middleware é um interceptador de requisições.

  • Pode interromper uma requisição
  • Tem acessos à todos os parâmetros
  • Pode alterar dados em uma requisição
const express = require('express');
const { uuid, isUuid } = require('uuidv4');
const app = express();
app.use(express.json());
function logRequests(request, response, next){
const { method, url } = request;
const logLabel = `[${method.toUpperCase()}] ${url}`;
return next();
};
function validateProjectId(request, response, next){
const { id } = request.params;
if (!isUuid(id)) return response.status(400).json({ error: 'Invalid project ID. ' });
return next();
};
app.use(logRequests); // Middleware pode ser chamado para todas as rotas.
app.use('/projects/:id', validateProjectId); //Middleware pode ser chamado para uma rota específica.
view raw middleware.js hosted with ❤ by GitHub

Assim fica o arquivo no final, com o express, as rotas e os middlewares:

const express = require('express');
const { uuid, isUuid } = require('uuidv4');
const projects = [];
const app = express();
app.use(express.json());
//Middleware
function logRequests(request, response, next){
const { method, url } = request;
const logLabel = `[${method.toUpperCase()}] ${url}`;
console.log(logLabel);
console.time(logLabel);
console.log(1);
next();
console.log(2);
console.timeEnd(logLabel);
};
//Middleware
function validateProjectId(request, response, next){
const { id } = request.params;
if (!isUuid(id)) return response.status(400).json({ error: 'Invalid project ID. ' });
return next();
};
app.use(logRequests);
app.use('/projects/:id', validateProjectId); //Middlewares podem ser chamados aqui, ou em cada rota
app.get('/projects', (request, response) => {
console.log(3);
const { title, owner } = request.query;
const results = title ? projects.filter(project => project.title.includes(title)) : projects;
return response.json(results);
});
app.post('/projects', (request, response) => {
const { title, owner } = request.body;
const project = { id: uuid(), title, owner };
projects.push(project);
return response.json(project);
});
app.put('/projects/:id', (request, response) => {
const { id } = request.params;
let projectIndex = projects.findIndex( project => project.id === id );
if ( projectIndex < 0 ) return response.status(400).json({ error: 'Project not found.' });
const project = {
id,
title,
owner
};
projects[projectIndex] = project;
return response.json(project);
});
app.delete('/projects/:id', (request, response) => {
const { id } = request.params;
let projectIndex = projects.findIndex( project => project.id === id );
if ( projectIndex < 0 ) return response.status(400).json({ error: 'Can not delete.' });
projects.splice(projectIndex, 1);
return response.send();
});
app.listen(3333, () => {
console.log('back-end started! 🚀');
});
view raw index.js hosted with ❤ by GitHub

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • --last-failed: Zero in on just the tests that failed in your previous run
  • --only-changed: Test only the spec files you've modified in git
  • --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Practical examples included!

Watch Video 📹️

Top comments (0)

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed
  • 2:34 --only-changed
  • 4:27 --repeat-each
  • 5:15 --forbid-only
  • 5:51 --ui --headed --workers 1

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Watch Full Video 📹️

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay