如何将带有令牌的标头(随每个请求更改)附加到来自node.js中的api的所有传出请求

时间:2018-03-10 21:20:28

标签: node.js httprequest

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)
    }
})

除了上述标题之外,我如何在每个请求中附加一个可以有令牌(令牌每10分钟到期一次)的标头。就像接受每个传出请求一样,获取新令牌并将其添加到标题中。

1 个答案:

答案 0 :(得分:0)

我会创建一个名为getOptions的函数,或类似的东西,因此每次创建一个请求时,都会调用该函数并根据需要创建头文件。

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'}
    };
}

每当你打电话请求时,你都会这样做:

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