nativescript 全局 http 标头

问题描述 投票:0回答:2

有没有办法使用 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'
});
nativescript
2个回答
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
中。


0
投票

我有同样的要求,在尝试了多种方法(包括尝试覆盖默认的 http.request 方法)之后,我最终采用了自定义 http 模块方法,在您的项目中创建一个新的 .js (或 .ts) 文件示例:httpCustomModule.js 包含以下内容:

const httpModule = require("@nativescript/core/http");
const configTbl = require("~/Util/db/configTbl"); //this can be applicationSettings

// Function to load cookies from local storage
//This could be cookies, or any other header type
function loadCookies() {
  //replace the below by appSettings.getString("Cookies") or replace with whatever data store you're using to save & retrieve your session cookies
  return configTbl.getAuthenticationCookies().then(cookies => {
    return cookies ? ? null;
  });
}

// Custom request function
function customRequest(options) {
  return loadCookies().then(cookies => {
    if (cookies) {
      options.headers = options.headers || {};
      options.headers['Cookie'] = cookies;
    }

    // Call the original http.request method with the modified options
    return httpModule.request(options);
  });
}

module.exports = {
  request: customRequest
};

然后,只需在您的视图模型中或在您发起 http 请求的任何位置,替换

const httpModule = require("@nativescript/core/http");

const httpModule = require("YourCustomHttpModulePath");

© www.soinside.com 2019 - 2024. All rights reserved.