[英]How to define Global Variable in Node/Express after Post/Get Request?
如何在 Post/Get 请求后在 Node/Express 文件中定义全局变量? 对于支付系统需要定义支付 id,它是在 POST 请求之后收到的。 所以我需要获取当前付款 ID 并动态传递给下一个获取请求。 一切正常,而不是动态传递付款 ID。 我怎样才能做到这一点?
我项目中的示例代码:
let paymentId;
app.post("/api/payments", (req, res) => {
var { body } = req;
var data = JSON.stringify({
amount: {
currency: "GEL",
total: body.amount,
subTotal: 0,
tax: 0,
shipping: 0,
},
returnurl: "http://localhost:3000/success",
userIpAddress: "127.0.0.1",
expirationMinutes: "5",
methods: [5, 7, 8],
callbackUrl: "url",
preAuth: true,
language: "EN",
merchantPaymentId: "P123123",
saveCard: false,
});
axios({
method: "post",
url: "https://api.tbcbank.ge/v1/tpay/payments",
headers: {
"Content-Type": "application/json",
apikey: apiKey,
Authorization: `Bearer ${token}`,
},
data,
})
.then(function (response) {
res.json(response.data);
paymentId = response.data.paymentId
})
.catch(function (error) {
console.log(error);
});
});
// 获取支付信息
app.get("/api/payments", (req, res) => {
var config = {
method: "get",
url: `https://api.tbcbank.ge/v1/tpay/payments//${paymentId}`,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
apikey: apiKey,
Authorization: `Bearer ${token}`,
},
};
axios(config)
.then(function (response) {
res.json(response.data);
})
.catch(function (error) {
console.log(error);
});
});
您可以创建一个空的 object 并分配新属性或删除/重新分配现有属性。 这是一个示例实现:
const memory = {};
app.post('/api/payments', (req, res) => {
const randomId = Math.floor(Math.random() * 1000) + 1;
memory.paymentId = randomId;
res.send(`Created random paymentId: ${paymentId}`);
});
app.get('/api/payments', (req, res) => {
res.json({paymentid: memory.paymentId});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.