request-ajax error handler for express
$ npm install --save express-request-ajax-error
Below is a example of usage. test/fixture/app.js also has a similar example.
var express = require('express');
var ajax = require('request-ajax');
var requestAjaxError = require('express-request-ajax-error');
var app = express();
app.use(function(req, res, next) {
// bind error handler to `res.locals`
res.locals.apiError = requestAjaxError(req, res, next);
});
app.get('/', function(req, res, next){
ajax({
url: 'http://my-api.com/test.json'
// use as callback
error: res.locals.apiError,
success: function(){
res.send('ok');
}
});
});
If the API returns a 401 code you should logout the user. Provide a logout callback and the module will do it for you.
res.locals.apiError = requestAjaxError(req, res, next, function(){
// logout user here
res.clearCookie('my_login_cookie');
res.redirect('/');
});
Variables provided with the error object:
err.url
API url that has caused iterr.status
API HTTP request statusCode
Backbone.ajax error handler that maps this module according to Backbone.sync. Below is a example of usage.
// one time setup
Backbone.ajax = require('request-ajax');
// ...
// bind to express request
var backboneRequestAjaxError = require('express-request-ajax-error').backbone(req, res, next, function(){
res.redirect('/');
});
// ...
// use
var model = new Backbone.Model();
model.fetch({
error: backboneRequestAjaxError
});