express - post 适用于 request 模块,但不适用于 axios
问题描述
我为此花了两个小时的时间,想知道新鲜的眼睛是否有帮助。
我正在尝试联系 auth0 以获取管理 API 的访问令牌。
提供示例代码,使用请求模块,完美运行(我已经替换了密钥/秘密值):
var request = require("request");
var options = { method: 'POST',
url: 'https://dev-wedegpdh.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body: '{"client_id":"myID","client_secret":"mySecret","audience":"https://dev-wedegpdh.auth0.com/api/v2/","grant_type":"client_credentials"}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
res.json(JSON.parse(response.body).access_token)
});
我将我的 ID 和 Secret 存储在 .env 文件中,因此能够对此进行调整,这也可以正常工作:
var options = { method: 'POST',
url: 'https://dev-wedegpdh.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body:
JSON.stringify({
grant_type: 'client_credentials',
client_id: process.env.auth0AppKey,
client_secret: process.env.auth0AppSecret,
audience: 'https://dev-wedegpdh.auth0.com/api/v2/'})
}
request(options, function (error, response, body) {
if (error) throw new Error(error)
res.json(JSON.parse(response.body).access_token)
})
我尝试使用 axios 发出完全相同的请求,但收到 404 错误:
let response = await axios.post(
'https://dev-wedegpdh.auth0.com/api/v2/oauth/token',
JSON.stringify({
grant_type: 'client_credentials',
client_id: process.env.auth0AppKey,
client_secret: process.env.auth0AppSecret,
audience: 'https://dev-wedegpdh.auth0.com/api/v2/'
}),
{
headers: {'content-type': 'application/json'},
}
)
我已经为 post 功能尝试了几种不同的格式或配置,包括在 此处和此处找到的那些等。
有人看到我做错了吗???
解决方案
在 axios post body 中,需要以 JSON 格式发送数据,无需使用 JSON.stringify。
let response = await axios.post(
"https://dev-wedegpdh.auth0.com/api/v2/oauth/token",
{
grant_type: "client_credentials",
client_id: process.env.auth0AppKey,
client_secret: process.env.auth0AppSecret,
audience: "https://dev-wedegpdh.auth0.com/api/v2/"
},
{
headers: { "content-type": "application/json" }
}
);
推荐阅读
- javascript - C++ 附加组件不在 express api 路由内部运行,但在外部运行
- oracle - Oracle Apex 发送附有交互式报告或区域的电子邮件
- r - 如何将单变量时间序列转换为 R 中的向量
- python - 使用欧几里得距离计算 2 个直方图之间的距离
- javascript - 覆盖expressjs中端点的响应状态
- reactjs - 下一个认证 | 当用户对象有太多项目时,会话请求没有数据
- python - 无法获取经理帐户的 Google Ads 指标,无法获得客户帐户的权限
- reactjs - Messenger 客户聊天 - 带有下一个主题的暗模式下的白色气泡
- java - TextView 不使用自定义字体包装内容
- python - 无法在 macos 上安装 boost-python