nativescript全局http标头

时间:2018-08-22 10:14:23

标签: nativescript

是否可以使用Nativescript将全局标头设置为http模块?

相反,这样做:

const http = require('http')

return http.request({
        url : ...,
        method: 'GET',
        headers: {
           'Authorization' : 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c',
           'Content-Type': 'application/json'
        }
});

我想要这样的东西:

const http = require('http')

http.headers = {
       'Authorization' : 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c',
       'Content-Type': 'application/json'
}

return http.request({
        url : ...,
        method: 'GET'
});

1 个答案:

答案 0 :(得分:0)

我对通用的http标头使用全局函数,例如

function getCommonHeaders() {
  return {
     "Content-Type": "application/json",
     "Authorization": "Bearer " + config.token
  }
}

然后在所有HTTP请求中使用它们

const http = require('http');

return http.request({
    url : ...,
    method: 'GET',
    headers: getCommonHeaders()
});

您可能还需要考虑将密钥/令牌存储在配置设置或application-settings中。