superagent global 401 handler

Created on 18 Jan 2016  路  8Comments  路  Source: visionmedia/superagent

I am using superagent to do my ajax data fetching job.

request
    .get('/some/end/point')
    .end(function(err, res) {

        if (err && res.status === 401) {
            // redirect to login
        }

        // do something with res.body

    });

many of my request need authentication check,
but is that possible to config if (err && res.status === 401) {} globally?

or I should repeat the code in every request I make ?

Most helpful comment

@allces

function authorizedGet(url) {
    return request.get(url)
        .use(unauthorizedRedirect);
}

All 8 comments

You can use like this:

var unauthorizedRedirect = function(req) {
  req.on('response', function (res) {
    if (res.status === 401) {
      console.dir('redirects')
      // redirect to login
    }
  });
};

request
  .get('/some/end/point')
  .use(unauthorizedRedirect)
  .end(function(err, res) {
    // do something with res.body
  });

still need add repeat code(use....) in every request

@allces

function authorizedGet(url) {
    return request.get(url)
        .use(unauthorizedRedirect);
}

thanks for replying,

But I got an question:
how do you know there is a 'response' event on req
and there is a use method?

seems they do not exist on the doc :pig:

@littlee
use method is used in superagent Plugins. I learnt response event from source code, so response event may be changed without notice.

great, learning from source code. :+1:

Since #1302 you can set a plugin for all requests from an agent.

@littlee since you want to avoid repetitive code, here you go:

  1. Define this somewhere in a module file
import superagent from "superagent";
export const request = superagent.agent()
    .use(function(req) {
        req.on('response', function (res) {
            if (res.status === 401) {
                console.dir('redirects')
            }
        });
    });

2, import from this module to use the request, instead of importing from superagent

import {request} from '../your/local/module';
request.get('/some/end/point')
           .end(function(err, res) {
              // do something with res.body
           });
Was this page helpful?
0 / 5 - 0 ratings