0

我创建了一个如下中间件:

const oAuth = (req, res, next) => {

    axios.post(tokenEndpoint, "", { params: {

        grant_type: process.env.GRANT_TYPE,
        client_id: process.env.CLIENT_ID,
        client_secret: process.env.CLIENT_SECRET,
        code: process.env.AUTHORIZATION_CODE,
       
    
    }}).then(response => {
        req.oAuth = response.data;
        //console.log(response.data);
        console.log(req.oAuth);
    }).catch(err => {
        console.error(err);
    })
    next();
}

module.exports = oAuth;

oauth 函数的响应/结果类似于:

{
  access_token: '1000.ddf6d96b4f3sadasdasdas55a2450ae13',
  refresh_token: '100dasdsadasdsadhgdhgfhdghdfghe427288',
  api_domain: 'https://www.oapis.com',
  token_type: 'Bearer',
  expires_in: 3600
}

现在在“index.js”文件中,我试图解构 oAuth 函数响应对象以访问属性access_token并将其放入 URL 中以发出发布请求,但我没有成功。我究竟做错了什么?

const express = require("express");
const axios = require("axios");
const oAuth = require("./oAuth.js");

const app = express();

app.use(oAuth);

var port = process.env.PORT || 3001;

const someAPI = "https://www.oapis.com/crm/v2/Leads";

app.get("/", async (req, res) => {
   
    try {
        const {access_token} = req.oAuth
                
        
        const response = await axios({
            method: "GET",
            url: someAPI,
            //timeout: 1000,
            headers: { Authorization: `Zoho-oauthtoken ${access_token}` },

        });
        return res.json(response.data);
        
    } catch (error) {
        console.log(error);
        if (error.response.status === 401) {
          res.status(401).json("Unauthorized to access data");
        } else if (error.response.status === 403) {
          res.status(403).json("Permission denied");
        } else {
          res.status(500).json("Whoops. Something went wrong");
        }
    };
});
4

1 回答 1

1

我建议在这里使用 async/await 来等待 oauth 响应,然后才修改请求对象以便将其进一步传递给next()回调。

const oAuth = async (req, res, next) => {
    try {
        const response = axios.post(tokenEndpoint, "", { params: {
            grant_type: process.env.GRANT_TYPE,
            client_id: process.env.CLIENT_ID,
            client_secret: process.env.CLIENT_SECRET,
            code: process.env.AUTHORIZATION_CODE,    
        }});
        console.log(response.data);
        req.oAuth = response.data;
    } catch (e) {
        console.log(e);
    }
    next();
}

module.exports = oAuth;
于 2021-06-11T14:52:59.733 回答