Skip to content

Instantly share code, notes, and snippets.

@chengmu
Created September 4, 2013 07:45
Show Gist options
  • Save chengmu/6433888 to your computer and use it in GitHub Desktop.
Save chengmu/6433888 to your computer and use it in GitHub Desktop.
express.js + node.js build up restful api
//使用express.js+ node.js搭建restful api
var express = require('express');
var app = express();
app.use(express.bodyParser());
var quotes = [
{ author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm possible'!"},
{ author : 'Walt Disney', text : "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you"},
{ author : 'Unknown', text : "Even the greatest was once a beginner. Don't be afraid to take that first step."},
{ author : 'Neale Donald Walsch', text : "You are afraid to die, and you're afraid to live. What a way to exist."}
];
app.listen(process.env.PORT || 3412);
app.get('/', function (req, res) {
res.json(quotes);
});
app.get('/quote/random', function (req, res){
var id = Math.floor(Math.random() * quotes.length);
var q = quotes[id];
res.json(q);
});
app.get('/quote/:id', function (req, res) {
if (quotes.length <= req.params.id || req.params.id<0) {
res.statusCode = 404;
return res.sentd('Error 404: no quote found');
}
console.log(req.params);
var q = quotes[req.params.id];
res.json(q);
});
app.post('/quote', function (req, res) {
if(!req.body.hasOwnProperty('author') || !req.body.hasOwnProperty('text') ) {
res.statusCode = 400;
return res.send('Error 400: Post Syntax Incorrect');
}
var newQuote = {
author : req.body.author,
text : req.body.text
};
console.log(newQuote);
quotes.push(newQuote);
res.json(true);
});
app.delete('/quote/:id', function (req, res) {
console.log(req);
if (quotes.length <= req.params.id || req.params.id<0) {
res.statusCode = 404;
return res.sentd('Error 404: no quote found');
}
quotes.splice(req.params.id, 1);
res.json(true);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment