Created
September 14, 2019 17:53
-
-
Save quentin-aslan/d9132ee1166a24a5facae7f40822d6d0 to your computer and use it in GitHub Desktop.
When i try to learn node js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = express(); | |
app.use(express.json()); | |
app.use(express.urlencoded({extended: true})) | |
const bikes = [ | |
{id: 1, color: 'blue'}, | |
{id: 2, color: 'red'} | |
]; | |
function varExists(variable) { | |
if (typeof req.body.color === "undefined") return false; | |
return true; | |
} | |
app.get('/api/bikes', (req, res) => { | |
res.send(bikes) | |
}) | |
.get('/api/bikes/:id', (req, res) => { | |
const bike = bikes.find(b => b.id === parseInt(req.params.id)); | |
res.send(bike); | |
}) | |
.post('/api/bikes/', (req, res) => { | |
if (varExists(req.body.color) || req.body.color.length < 3) return res.status(400).send('Color is required'); | |
const bike = { | |
id: bikes.length + 1, | |
color: req.body.color | |
}; | |
bikes.push(bike); | |
res.send(bike); | |
}) | |
.put('/api/bikes/:id', (req, res) => { | |
// Edit a bike | |
}) | |
.delete('/api/bile/:id', (req, res) => { | |
// Delete a bike | |
}); | |
const port = process.env.PORT || 3000; | |
app.listen(port, (req, res) => { | |
console.log('Server start listener on port ' + port + '...'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment