Created
June 13, 2016 20:42
-
-
Save MCheli/2eb480cd46a66e507219e70b6bcd832d to your computer and use it in GitHub Desktop.
NodeJS Server with REST API
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
var express = require('express'); | |
var morgan = require('morgan'); | |
var bodyParser = require('body-parser'); | |
var hostname = 'localhost'; | |
var port = 3000; | |
var app = express(); | |
app.use(morgan('dev')); | |
app.use(bodyParser.json()); | |
app.all('/dishes', function(req,res,next) { | |
res.writeHead(200, { 'Content-Type': 'text/plain' }); | |
next(); | |
}); | |
app.get('/dishes', function(req,res,next){ | |
res.end('Will send all the dishes to you!'); | |
}); | |
app.post('/dishes', function(req, res, next){ | |
res.end('Will add the dish: ' + req.body.name + ' with details: ' + req.body.description); | |
}); | |
app.delete('/dishes', function(req, res, next){ | |
res.end('Deleting all dishes'); | |
}); | |
app.get('/dishes/:dishId', function(req,res,next){ | |
res.end('Will send details of the dish: ' + req.params.dishId +' to you!'); | |
}); | |
app.put('/dishes/:dishId', function(req, res, next){ | |
res.write('Updating the dish: ' + req.params.dishId + '\n'); | |
res.end('Will update the dish: ' + req.body.name + | |
' with details: ' + req.body.description); | |
}); | |
app.delete('/dishes/:dishId', function(req, res, next){ | |
res.end('Deleting dish: ' + req.params.dishId); | |
}); | |
app.use(express.static(__dirname + '/public')); | |
app.listen(port, hostname, function(){ | |
//noinspection JSAnnotator | |
console.log(`Server running at http://${hostname}:${port}/`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment