【问题标题】:Axios returns a response code of 400 when making Basic Authenticationaxios做Basic Authentication时返回响应码400
【发布时间】:2021-11-08 15:44:58
【问题描述】:

我正在尝试使用basic authentication 流从邮递员的 api 端点获取访问令牌。

app.post('/epic', async (req:Request, res) => {
  const code = req.query.code as string
  const url = "https://api.epicgames.dev/epic/oauth/v1/token"
  const values = new URLSearchParams({
    code,
    client_id,
    client_secret,
    scope: "basic_profile",
    grant_type: "authorization_code",
  })

  console.log(code, values)

  try {
    const res = await axios.post(url, values, {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    })
    console.log(res.data)
    return res.data
  } catch (error: any) {
    console.error(error.message)
    throw new Error(error.message)
  }
})

它不断返回 400 错误请求。我是不是做错了什么?

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

【问题讨论】:

  • 分享更多错误信息
  • UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺
  • 查看控制台,axios.post 调用抛出了什么错误。所以,分享这个的输出:console.error(error.message) 来自你的 catch 块
  • 它说“请求失败,状态码为 400”并且代码参数未定义。但我是从邮递员那里传过来的。谢谢
  • 它是否在您的控制台上正确打印代码?我看到console.log(code, values),这是登录控制台吗?你怎么从邮递员那里调用API,你能分享一下

标签: javascript node.js api axios http-status-code-400


【解决方案1】:

req.query 在 URL 中为您提供查询参数(例如 https://www.somewebsite.com/api?code=supersecretcode),而在邮递员中您将其作为请求的正文提供。您可以通过以下两种方式进行:

  1. 在 URL 中使用查询参数,而不是在邮递员请求的正文中 - 这就像将请求正文中的所有内容移动到 URL (http://localhost:4000/epic?code=supersecretcode&grant_type=authorization_code&scope=basic_profile) 一样简单

  2. 在您的服务器中解析请求正文。我在这个例子中使用了有用的 body-parser 包:

const bodyParser = require("body-parser")

app.use(bodyParser.urlencoded({ extended: false })

app.post('/epic', async (req: Request, res) => {
  const { code } = req.body
  const url = "https://api.epicgames.dev/epic/oauth/v1/token"
  const values = new URLSearchParams({
    code,
    client_id,
    client_secret,
    scope: "basic_profile",
    grant_type: "authorization_code",
  })
  // ...
})

【讨论】:

  • 太棒了!我已经重写了查询,我得到了“代码”。但是请求没有得到解决。它仍然返回一个奇怪的 400 状态码
  • 也许您应该尝试使用res.status(200) 响应请求,这将提供状态为200。您还可以在响应中添加一些json,例如res.status(200).json({ data: res.data })
  • 也不要贪心或其他任何事情,但如果您点击我的问题上的绿色勾号表示我已经回答了您最初的问题,我将不胜感激:)
猜你喜欢
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
  • 2018-10-12
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
相关资源
最近更新 更多