【发布时间】:2021-06-12 17:35:55
【问题描述】:
我创建了如下中间件:
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 以发出发布请求,但我' m 没有成功。我做错了什么?
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");
}
};
});
【问题讨论】:
-
问题不在于你的解构赋值,而只是你的中间件从不调用
next。 -
@bergi 我做到了,但还是没用。
-
在调用 next 后您会收到响应,因此您的处理程序中没有
oAuth。这样做的一种方法是等待您在中间件中进行的 http 调用的响应。 -
@GabrielDillenburg 但是你做错了地方。修改请求后,您只能致电
next(),如果收到错误,则应致电next(error)。 -
@holymoof 我明白了。你能举个例子吗?tks!
标签: node.js post axios destructuring object-destructuring