谷歌的oauth2得到令牌的JavaScript POST请求(google oauth2 get

2019-10-24 01:35发布

我看到一些有关此问题和答案,但不明白该怎么做。 我得到这个错误: XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 400. XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 400. XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 400.正如我以前的帖子看到的,这是因为我不能让一个HTTP POST请求到另一台服务器。 我看到一些东西将JSONP,但不明白为什么。这是我用来发送请求的功能:

var url = 'https://accounts.google.com/o/oauth2/token';
var payload = {
    grant_type: 'authorization_code',
    code: authResult['code'],
    client_id: clientID,
    client_secret: clientSecret,
    redirect_uri: '',
    dataType: 'jsonp'
};

$.post(url, {
    form: payload
}, function(error, response, body) {
    console.log(body);
});

Answer 1:

你已经注册你的应用程序?

获取OAuth键值:

  • 访问谷歌云端控制台
  • 点击创建项目按钮
  • 输入项目名称,然后单击创建
  • 然后从侧栏API和验证,然后单击凭据选项卡上
    • 点击创建新客户端ID按钮
    • 应用类型:Web应用程序
    • 授权JavaScript来源: HTTP://本地主机:63342
    • 授权的重新导向URI: HTTP://本地主机:63342 / ...

注:确保你已经把你需要的API。

最重要的部分是: 授权的JavaScript来源: HTTP://本地主机:63342 ,需要autorize你的网站域名来访问API。

端点是不好用https://www.googleapis.com/oauth2/v3/token 谷歌文档 :

$.ajax({
    url: "https://www.googleapis.com/oauth2/v3/token",
    data: {
        code :"",
        client_id : "",
        client_secret : "",
        redirect_uri : "",
        grant_type : "authorization_code"
    },
    method: "POST",
    success: function(e){console.log(e)}
});


文章来源: google oauth2 get token javascript post request