javascript - 如何在浏览器的 reddit api 中使用 oauth?

标签 javascript api oauth reddit

我所做的一切都不起作用,而且我不断收到荒谬的 CORS 错误和其他问题。我只想做一个正常的誓言,通过浏览器登录用户。我想使用 snoowrap,但我什至无法使用它,因为我需要一个刷新 token 。

我已经授权该应用程序并从 API 中取回“代码”,然后我应该通过向 https://www.reddit.com/api/v1/access_token 发出发布请求来使用它.

但我每次都会收到 CORS 错误。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.reddit.com/api/v1/access_token. (Reason: missing token ‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.reddit.com/api/v1/access_token. (Reason: CORS request did not succeed).

代码:
const redirect_uri = 'https://EXAMPLE.com/reddit/';
const client_id = 'xxxxxxxxxxxxx';
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString); /*global URLSearchParams*/
const code = urlParams.get('code');

var snoowrap = window.snoowrap;






if (code) {
    console.log('code gotten', code);

    const data = {
        grant_type: 'authorization_code',
        code: code,
        redirect_uri: redirect_uri
    };

    ajax('https://www.reddit.com/api/v1/access_token', data, 'Basic client_id:', result => {
        console.log(result);

        const r = new snoowrap({
            userAgent: 'skeddit',
            clientId: client_id,
            clientSecret: 'fFP-6BKjFtvYpIkgFGww-c6tPkM',
            refreshToken: '',
        });

        r.getHot().map(post => post.title).then(console.log);
    });
}



//GET:  ajax(String url, Function success)
//POST: ajax(String url, Object postData, Function success)

function ajax(url, arg2, arg3, arg4) {
  if (typeof arg2 == 'function')
    var success = arg2;
  else {
    var postData = arg2;
    var headers = arg3;
    var success = arg4;
  }

  console.log('AJAX - STARTING REQUEST', url)

  //start new request
  var xhttp = new XMLHttpRequest({mozSystem: true});
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      success(JSON.parse(this.response));
      xhttp = null;
      console.log('AJAX - COMPLETE', this.response);
    }
  };

  if (postData) {
    //post request
    console.log('post data: ', postData);
    var formData = new FormData();

    for ( var key in postData ) {
      formData.append(key, postData[key]);
    }

    xhttp.open("POST", url, true); 
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.setRequestHeader("Authorization", headers);
    xhttp.send(formData);
  }
  else {
    //get request
    xhttp.open("GET", url, true); 
    xhttp.send();
  }

  return xhttp;
}

我什至不明白为什么有些东西会阻止我向公共(public) api 发出 POST 请求

最佳答案

经过数小时的搜索,我找到了解决方案:
如果您正在创建仅浏览器的 JS 应用程序(无服务器),您应该在 reddit console 中选择您的应用程序类型为“已安装的应用程序”(而不是“网络应用程序”) .
enter image description here
然后您必须发送一个 Authorization header ,其值为您的客户端 ID,如此处所述 reddit/wiki/OAuth2

  const fd = new FormData();
  fd.append("code", code);
  fd.append("grant_type", "authorization_code");
  fd.append("redirect_uri", "your_redirect_uri");

  const r = await fetch("https://www.reddit.com/api/v1/access_token", {
    headers: {
      Authorization:
        "Basic " + btoa(unescape(encodeURIComponent(CLIENT_ID + ":" + ""))),
    },
    method: "POST",
    body: fd,
  });

关于javascript - 如何在浏览器的 reddit api 中使用 oauth?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59900724/

相关文章:

javascript - WSH 中的日期时间格式(以及与日期对象的差异)

javascript - 获取对象属性

javascript - AngularJS 在 for 属性中写入变量后添加空格

java - Android AsyncTask #2 调用 detach()

r - 将 Terrain 类型的 Google API 静态 map 导入没有标签的 R

jquery - 如何通过 JSON 或 HTTP 代理访问 Rally REST API JSON 响应?

javascript - 如何在 javascript 中传递变量而不使用参数?

oauth - 如何避免 fatal error : Uncaught OAuthException when using cron job

java - 在js或java中为twitter的pentaho客户端生成oauth签名

android - 我应该在 Android 客户端中验证 OAuth2 token ,还是 App Engine 本身会根据传递给后端 API 的凭据对用户进行身份验证?