从 Notion API 获取访问令牌时无法 POST /v1/oauth/token

问题描述 投票:0回答:1

我正在尝试与 Notion 的 OAuth API 集成,但在尝试使用 POST 请求获取访问令牌时遇到了问题。我的代码片段如下:

const authHeader = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64");
const tokenResponse = await fetch("https://api.notion.com/v1/oauth/token", {
  method: "POST",
  headers: {
    Authorization: `Basic ${authHeader}`,
    "Content-Type": "application/json",
    "Notion-Version": "2022-06-28",
    Accept: "application/json",
  },
  body: JSON.stringify({
    grant_type: "authorization_code",
    code: authCode,
    redirect_uri: "http://localhost:3000/api/notion/callback",
  }),
});

if (!tokenResponse.ok) {
  // Log response details to help with debugging
  const text = await tokenResponse.text(); // Read response as plain text
  console.error("Error response: ", text);
  throw new Error(`Request failed with status ${tokenResponse.status}`);
}

但是,我收到以下错误:

Error response:  
<!DOCTYPE html> 
<html lang="en"> 
<head> <meta charset="utf-8"> <title>Error</title> </head> 
<body> <pre>Cannot POST /v1/oauth/token</pre> </body> 
</html> 
  • 根据 Notion 的 API 文档,确保 URL https://api.notion.com/v1/oauth/token 正确。
  • 确认 CLIENT_ID 和 CLIENT_SECRET 已正确填充并以 base64 编码。
  • 验证请求正文中的 grant_type、code 和 redirect_uri 参数是否正确设置。
javascript next.js oauth-2.0 notion-api
1个回答
0
投票

我是 Efe Karakaya,我会尽力帮助您解决这个问题。

由于我无法访问整个代码,我将提及可见代码中的推论和一些错误。

首先:您使用的授权标头格式似乎不正确。对于 OAuth 令牌请求,授权标头通常不应包含 Basic 前缀。相反,如果需要,请在检索访问令牌后使用承载令牌。只需在此处将其删除,因为它不是令牌端点的标准:

headers: {
  "Content-Type": "application/json",
  "Notion-Version": "2022-06-28",
},

其次: 身体结构。确保主体参数的格式按照 Notion API 文档正确。请求正文的结构应正确,并包含必要的参数。

您的错误处理非常棒,因为它记录了响应正文。 HTML 响应表明 POST 请求可能未到达预期端点。值得检查一下您是否位于任何可能影响出站请求的代理或防火墙后面。

const tokenResponse = await fetch("https://api.notion.com/v1/oauth/token", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Notion-Version": "2022-06-28",
  },
  body: JSON.stringify({
    grant_type: "authorization_code",
    code: authCode,
    redirect_uri: "http://localhost:3000/api/notion/callback",
    client_id: CLIENT_ID,
    client_secret: CLIENT_SECRET,
  }),
});

if (!tokenResponse.ok) {
  const text = await tokenResponse.text();
  console.error("Error response: ", text);
  throw new Error(`Request failed with status ${tokenResponse.status}`);
}

// If successful, parse the JSON response
const tokenData = await tokenResponse.json();
console.log(tokenData);

我要说的就是这些。我自己编辑了代码,写在下面。我希望我能帮上忙。

谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.