संबोधित करने के लिए एक्सप्रेस अपने वेब ढांचा होगा एक API रूट करने के लिए express-resource (Github) मिडलवेयर को देखने के लिए जा रहा द्वारा API तक पहुंच जाएगा। आप संसाधनों को परिभाषित करते हैं और यह आपके लिए बहुत कम बॉयलरप्लेट के साथ रीस्ट-स्टाइल रूटिंग को तार देगा।
app.resource('horses', require('./routes/horses'), { format: json })
को देखते हुए ऊपर, एक्सप्रेस-संसाधन कार्यों आपूर्ति, डिफ़ॉल्ट रूप से JSON लौटने के लिए सभी REST- शैली मार्गों ऊपर हुक होगा। routes/horses.js
में, आप, कि संसाधन के लिए कार्रवाई निर्यात की तर्ज पर:
exports.index = function index (req, res) {
// GET http://yourdomain.com/horses
res.send(MyHorseModel.getAll())
}
exports.show = function show (req, res) {
// GET http://yourdomain.com/horses/seabiscuit
res.send(MyHorseModel.get(req.params.horse))
}
exports.create = function create (req, res) {
// PUT http://yourdomain.com/horses
if (app.user.canWrite) {
MyHorseModel.put(req.body, function (ok) { res.send(ok) })
}
}
// ... etc
आप अलग अलग प्रतिनिधित्व के साथ प्रतिक्रिया कर सकते हैं:
exports.show = {
json: function (req, res) {
// GET http://yourdomain/horses/seabiscuit.json
}
, xml: function (req, res) {
// GET http://yourdomain/horses/seabiscuit.xml
}
}
Middlewares express-resource तरह नोड और एक्सप्रेस बहुत आसान के साथ जीवन बना सकते हैं, ले यह देखने के लिए कि क्या आपको वह चाहिए जो गिथब पर उदाहरणों के माध्यम से देखें।
स्रोत
2012-04-19 15:32:19