简体   繁体   中英

How to attach a header with the token(which changes with each request) in to all outgoing requests from an api in node.js

var request = require('request');

// Set the headers
var headers = {
    'User-Agent':       'Super Agent/0.0.1',
    'Content-Type':     'application/x-www-form-urlencoded'
}

// Configure the request
var options = {
    url: 'http://samwize.com',
    method: 'GET',
    headers: headers,
    qs: {'key1': 'xxx', 'key2': 'yyy'}
}

// Start the request
request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        // Print out the response body
        console.log(body)
    }
})

In addition to the above headers, How can I attach a header which can have a token (token expires every 10 minutes) in every request. Like inetercepting every outgoing request, getting the new token and adding it to header.

I would create a function called getOptions, or something like that, so each time a request is created the function is called and headers are created as needed.

var createToken = function() {
    // Can be generated based on date/time.
    return 'token'; 
}

var getOptions = function() {
    var headers = {
        'User-Agent':       'Super Agent/0.0.1',
        'Content-Type':     'application/x-www-form-urlencoded',
        'Token': createToken();
    };

    return {
        url: 'http://samwize.com',
        method: 'GET',
        headers: headers,
        qs: {'key1': 'xxx', 'key2': 'yyy'}
    };
}

And whenever you call request you do:

// Start the request
request(getOptions(), function (error, response, body) {
    if (!error && response.statusCode == 200) {
        // Print out the response body
        console.log(body)
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM