Skip to content

Instantly share code, notes, and snippets.

@hadashiA
Created March 9, 2013 15:55
Show Gist options
  • Save hadashiA/5124606 to your computer and use it in GitHub Desktop.
Save hadashiA/5124606 to your computer and use it in GitHub Desktop.
expressのreq.format()を、urlの拡張子で判別してくれるようにする ref: http://qiita.com/items/e14e4eb1e6d748af15c4
app.get('/hoge.:format', function(req, res) {
res.format({
json: function(req, res) {
res.send({a: 1});
},
html: function(req, res) {
// ブラウザから /index.json にアクセスしてもこっちが実行される
res.render('index');
},
default: function(req, res) {
res.send(406);
}
});
});
var __accepts = express.request.accepts;
express.request.accepts = function(type) {
var format = this.params.format
, i;
if (util.isArray(type)) {
for (i = 0; i < type.length; i++) {
t = type[i];
if (type[i] === format) {
return type[i];
}
}
} else if (type === this.params.format) {
return type;
}
return __accepts.call(this, type);
};
var __is = express.request.is;
express.request.is = function(type) {
return this.params.format === type || __is.call(this, type);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment