gpt4 book ai didi

javascript - 在 Node.js 中将 token 传递给另一个请求

转载 作者:行者123 更新时间:2023-12-03 01:04:22 24 4
gpt4 key购买 nike

在第一个请求中,我要求外部服务器提供 token 。我明白了。然后我想在另一个请求中使用它。一切都在express.js 中完成。将其提供给另一个请求的最佳解决方案是什么?

看起来像这样:

const express = require('express');
const axios = require('axios');
const config = require('./config');

const app = express();

axios.post('URL1', {
email: config.email,
password: config.password,
})
.then(function(response) {
console.log(response.data.token); //here I' getting the token
})
.catch(function(error) {
console.log(error);
});


const headers = { headers: { 'Authorization': 'Token ' + token } }; //here I would like to use (for the use of a second request)

axios.get('URL2', headers)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});

const PORT = process.env.PORT || 5000;
app.listen(PORT);

当然我不能只将它分配给变量。谢谢您的帮助!

最佳答案

您可以在另一个函数中调用它,如下所示。

const express = require('express');
const axios = require('axios');
const config = require('./config');

const app = express();

axios.post('URL1', {
email: config.email,
password: config.password,
}).then((response) => {
// calling function here
return handleToken(response.data.token);
console.log(response.data.token); //here I' getting the token
}).catch((error) => {
console.log(error);
});

//second request will be handled here
const handleToken = (token) => {
const headers = { headers: { 'Authorization': 'Token ' + token } };
//here I would like to use (for the use of a second request)

axios.get('URL2', headers)
.then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
});
}

const PORT = process.env.PORT || 5000;
app.listen(PORT);

最好编写一个单独的函数以避免回调 hell 。

编辑 - 带异步/等待的路由

app.get('/', async (req, res)=>{
try {
let result = await axios.post('URL1', { email: config.email, password: config.password });
let final = await handleToken(response.data.token);
// other operations here
console.log(result);
} catch (err) {
//handle error here
console.error(err);
}
})

//second request will be handled here
const handleToken = async (token) => {
try {
const headers = { headers: { 'Authorization': 'Token ' + token } };
let response = await axios.get('URL2', headers);
return response;
} catch (err) {
throw err;
}
}

关于javascript - 在 Node.js 中将 token 传递给另一个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52478240/

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