Reddit API /api/me 无法正常工作

Reddit API /api/me unable to make it work

我设法让 Reddit OAuth 工作,它被重定向到我的主页。 我得到一个 URL 像 http://localhost:3000/?state=XEA12&code=6p4pAyle2EWGVwIBlFJ6ERXjxKg

现在,当我尝试 /api/me 等其他 API 时。我无法让它工作。我还将我的应用程序的范围设置为身份。

这是我写的代码片段:

import axios from "axios";
import useSWR from "swr";

const link = "https://www.reddit.com/api/v1/me";

const config = {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    Authorization: "bearer 6p4pAyle2EWGVwIBlFJ6ERXjxKg",
  },
};

const fetcher = (url) => axios.get(url, config).then((res) => res);

export default function Home() {
  const { data, error } = useSWR(link, fetcher);
  if (error) return <div>failed to load </div>;
  if (!data) return <div>loading...</div>;
  return <div>{JSON.stringify(data)}</div>;
}

你能告诉我我做错了什么吗?是因为 headers 还是我需要传递其他东西?

根据文档,您需要先使用 code 参数检索 access_token。方法如下:https://github.com/reddit-archive/reddit/wiki/OAuth2#retrieving-the-access-token

然后您可以在不记名身份验证中使用 access_token。还有另一个注意事项:API 应向 https://oauth.reddit.com 发出带有不记名令牌的请求,而不是 www.reddit.com。 希望它会有所帮助