【问题标题】:Calling reddit api to get access token is being blocked by CORS policy调用 reddit api 以获取访问令牌被 CORS 策略阻止
【发布时间】:2021-07-20 21:28:20
【问题描述】:

我正在尝试在我的反应应用程序中使用 reddit api。但是当我尝试获取访问令牌时,出现以下错误。

    const response = await axios({
      method: "post",
      url: "https://www.reddit.com/api/v1/access_token",
      auth: {
        user: process.env.REACT_APP_REDDIT_CLIENT_ID,
        password: process.env.REACT_APP_REDDIT_CLIENT_SECRET,
      },
      data: {
        grant_type: "authorization_code",
        code: code,
        redirect_uri: "http://localhost:3000/login",
      },
    });

我是 Reddit Api 和 Oauth 的新手,所以我无法真正理解问题所在。

【问题讨论】:

    标签: javascript api oauth cors reddit


    【解决方案1】:

    我找到了解决方案。问题是发送的参数不能是 json 格式。 所以我不得不将它们更改为 url 编码。

     const params = new URLSearchParams();
          params.append("grant_type", "refresh_token");
          params.append("refresh_token", refreshToken);
    
          const config = {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
            auth: {
              username: process.env.REACT_APP_REDDIT_CLIENT_ID,
              password: process.env.REACT_APP_REDDIT_CLIENT_SECRET,
            },
          };
    
          const response = await axios.post(getPrefix(url), params, config);
    

    也是因为我的本地环境是http。它导致了cors问题。所以我在我的网址前加上了cors-anywhere,它可以工作。如前所述,我尝试使用reddit.local,但它似乎不起作用。

    【讨论】:

      猜你喜欢
      • 2021-04-15
      • 2021-06-22
      • 2019-11-01
      • 2021-10-15
      • 2023-01-10
      • 2020-08-20
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多