Skip to content

Instantly share code, notes, and snippets.

@faustoct1
Created June 28, 2022 23:54
Show Gist options
  • Save faustoct1/c9ba631913f4323895014b7e84218b84 to your computer and use it in GitHub Desktop.
Save faustoct1/c9ba631913f4323895014b7e84218b84 to your computer and use it in GitHub Desktop.
Exemplo simples de api com express nodejs
/*
yarn add express body-parser cors
node index.js
*/
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const cors = require('cors');
app.use(cors());
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
app.get('/api', (req, res) => {
const {query} = req
const json = {}
for (const [key, value] of Object.entries(query)) {
json[key] = value
}
res.json({ data: json })
})
app.get('/api/user/:id', (req, res) => {
const {params} = req
console.log(params)
res.json({ data: params })
})
app.post('/api', (req, res) => {
const {body} = req
const json = {}
for (const [key, value] of Object.entries(body)) {
json[key] = value
}
res.json({ data: json })
})
app.listen(5000)
Teste a api via curl
//fazendo um get /api
curl -X GET 'http://localhost:5000/api?username=code365&website=code365.web.app'
//fazendo um post /api com json
curl -X POST 'http://localhost:5000/api' -H 'Content-Type: application/json' -d '{"username":"code365","website":"code365.web.app"}'
//fazendo um get /api/user/:id
curl -X GET 'http://localhost:5000/api/user/1'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment