mirror of
https://github.com/jsbin/jsbin.git
synced 2026-02-01 16:46:05 +00:00
44 lines
1.4 KiB
JavaScript
44 lines
1.4 KiB
JavaScript
// Custom middleware used by the application.
|
|
module.exports = {
|
|
// Transparently handle JSONP. Although this does require wrapping the
|
|
// Request#send() method which is a bit nasty. Other alternative is to
|
|
// always pass the response on and include this middleware after the
|
|
// routes.
|
|
jsonp: function () {
|
|
return function (req, res, next) {
|
|
var _send = res.send;
|
|
res.send = function (body) {
|
|
var callback = req.param('callback'),
|
|
isJSONP = res.get('Content-Type') === 'application/json' && callback;
|
|
|
|
if (body && req.method !== 'HEAD' && isJSONP) {
|
|
res.contentType('js');
|
|
body = callback + '(' + body.toString().trim() + ');';
|
|
}
|
|
_send.call(this, body);
|
|
};
|
|
next();
|
|
};
|
|
},
|
|
// Check for ajax requests and set the Request#ajax flag to true.
|
|
ajax: function () {
|
|
return function (req, res, next) {
|
|
req.ajax = false;
|
|
if ((req.get('X-Requested-With') || '').toLowerCase() === 'xmlhttprequest') {
|
|
req.ajax = true;
|
|
}
|
|
next();
|
|
};
|
|
},
|
|
// Redirect urls with trailing slashes to their non-trailing counterpart,
|
|
// requires the "strict routing" setting to be false.
|
|
noslashes: function () {
|
|
return function (req, res, next) {
|
|
if (req.path !== '/' && req.path.slice(-1) === '/') {
|
|
res.redirect(301, req.path.slice(0, -1));
|
|
}
|
|
next();
|
|
};
|
|
}
|
|
};
|