将令牌传递给Node.js中的另一个请求

时间:2018-09-24 11:21:42

标签: javascript node.js express

在第一个请求中,我要求外部服务器提供令牌。我明白了。然后,我想在另一个请求中使用它。所有操作均在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);

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

1 个答案:

答案 0 :(得分:1)

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

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);

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

编辑-具有ASYNC / AWAIT的路由

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;
    }
}