首页 > 解决方案 > 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 功能尝试了几种不同的格式或配置,包括在 此处此处找到的那些等。

有人看到我做错了吗???

标签: expressrequestaxiosauth0

解决方案


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

推荐阅读