簡體   English   中英

從中間件響應中解構賦值 object

[英]Destructuring assignment object from a middleware response

我創建了一個如下中間件:

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 function 的響應/結果類似於:

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

now in the "index.js" file I'm trying to destructure the oAuth function response object to access the attribute access_token and put it in the URL to make a post request, but I'm not succeeding. 我究竟做錯了什么?

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

我建議在這里使用 async/await 來等待 oauth 響應,然后才修改請求 object 以便將其進一步傳遞給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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM