request / request-promise

The simplified HTTP request client 'request' with Promise support. Powered by Bluebird.
ISC License
4.77k stars 297 forks source link

Question : change defaults() options #337

Open ghost opened 4 years ago

ghost commented 4 years ago

Hi,

My app needs an authentication token to request an API. This token must be included in the header of each request (except the authentication request). Because it can expire my application must be able to request a new one (and must therefore remove the old one from the headers to do it)

So, is it possible to modify the options declared with the default() method ? Or must I store my token in a varriable and include the header in each request ?

Thanks in advance

An example of what I need

const rp = require('request-promise').defaults({
  uri: "myUrl",
  method: 'POST',
  headers: {
    'x-app': 'myApp',
  },
});

// manage (define, modify, ...) the header token
function login() {
  const options = { body: { 'a specific body Object' } };

  // if exists, delete the current token from headers
  if(rp.defaults.headers['my-token'])
    delete rp.defaults.headers['my-token'];

  return rp(options).then(result => {
    // add the new token in the defaults headers
    rp.defaults.headers['my-token'] = result.token

    // something else
  });
}

// token is in defaults options
function anotherFunction() {
  const options = { body: { 'an other body Object'} };
  return rp(options).then(result => {
    // do something else
  });
}