Skip to content

Instantly share code, notes, and snippets.

@quentin-aslan
Created September 14, 2019 17:53
Show Gist options
  • Save quentin-aslan/d9132ee1166a24a5facae7f40822d6d0 to your computer and use it in GitHub Desktop.
Save quentin-aslan/d9132ee1166a24a5facae7f40822d6d0 to your computer and use it in GitHub Desktop.
When i try to learn node js
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