gpt4 book ai didi

javascript - 更新跨项目导出的对象

转载 作者:行者123 更新时间:2023-11-30 20:11:30 24 4
gpt4 key购买 nike

我有以下与其他文件共享的对象

/实用程序/ token

module.exports = (function() {
const cache = {
access_token: 'jhkjfdhgkjhfkjmvbnmvcmgkjcvbnbfjhxvnm',
expires_in: 2592000,
token_type: 'Bearer'
};
return {
get(key) {
return cache[key];
},
set(key, val) {
cache[key] = val;
}
};
}());

在其他文件中,我尝试使用 SET 方法更新对象

const router = require('express').Router();
const _ = require('lodash');

const config = require('../config');
const axios = require('axios');
const errors = require('../utils/errors');
const constants = require('../utils/constants');
const jwtTokenService = require('../utils/jwt-token-service');
const cache = require('../utils/jwtToken'); // imported up here

router.get('/', (req, res) => {

const httpSearchAddressUXConfig = {
headers: Object.assign(res._headers, {
Authorization: `Bearer ${cache.get('access_token')}` // I am using get function to retrieve the value
}),
method: 'GET',
url: 'http://getUser/12345',
timeout: config.app.enterpriseHTTPTimeout
};
axios(httpSearchAddressUXConfig)
.then((result) => {
res.status(200).json(result);
})
.catch((err) => {
const errorList = err.response.data.errorList;
// res.status(401).json(errorList);
_.forEach(errorList, (element) => {
if (element.code === 'AUTH0007' || element.code === 'AUTH0003') {
jwtTokenService.getJwtToken(req, res).then((data) => {
cache.set('access_token', data.access_token); //updating the value up here
return axios(httpSearchAddressUXConfig);

// when I make this call it is taking the default value from the /utils/token through GET

})
.then(response => res.status(200).json(response))
.catch((errResponse) => {
res.status(401).json(errResponse.response.data.errorList);
});
}
});
});
});
module.exports = router;

上面的 SET 方法工作正常,但 cache.access_token 的值没有得到更新。所以每次我需要更新的 token 时我都需要进行一次设置调用。

我想在调用 SET 方法时更改 cache.access_token 的值,并在所有端点通过 GET 访问该值

const cache = {
access_token: 'jhkjfdhgkjhfkjmvbnmvcmgkjcvbnbfjhxvnm',
// need to change when ever SET is called.
expires_in: 2592000,
token_type: 'Bearer'
};

最佳答案

使用函数生成 axios 配置。您已经通过调用 cache.get('access_token') 创建了一次配置,使用相同的对象将不会再次调用 cache.get。使用这样的函数

function makeAxiosConfig(headers) {
return {
headers: Object.assign({}, headers, {
Authorization: `Bearer ${cache.get('access_token')}`
}),
method: 'GET',
url: 'http://getUser/12345',
timeout: config.app.enterpriseHTTPTimeout
}
}

// then inside you express middleware use it as follows
axios(makeAxiosConfig(res._headers)).then(() => {
// do something
}).catch(ex => {
// update token
return axios(makeAxiosConfig(res._header);
});

关于javascript - 更新跨项目导出的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52373604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com