import request from 'superagent';
const self = this;
request
.post('https://github.com/login/oauth/access_token')
.set('Content-Type', 'multipart/form-data')
.query({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
callback: 'http://127.0.0.1:3000/callback',
code,
state,
})
.end((err, res) => {
const token = res.body.access_token;
console.log(token);
self.setToken(token);
});
上面的代码会给我这样的错误
The code above will give me an error like this
XMLHttpRequest 无法加载https://github.com/login/oauth/access_token?client_id=112asdecf3805fdada12&…127.0.0.1%3A3000%2Fcallback&code=434ebd7bb98d9809bf6e&state=HelloWorld1234.请求中不存在Access-Control-Allow-Origin"标头资源.因此,不允许使用来源 'http://127.0.0.1:3000'访问.
XMLHttpRequest cannot load https://github.com/login/oauth/access_token?client_id=112asdecf3805fdada12&…127.0.0.1%3A3000%2Fcallback&code=434ebd7bb98d9809bf6e&state=HelloWorld1234. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access.
我不知道为什么即使我已经使用 github 注册了 oauth 应用程序并且回调 url 是 http://127.0.0.1:3000/callback
I have no idea why even though I've registered the oauth application with github and callback url is http://127.0.0.1:3000/callback
虽然所有实际的 GitHub API 端点通过发送正确的响应头来支持 CORS,它是 一个已知的问题 用于创建 OAuth 访问令牌的 https://github.com/login/oauth/access_token
端点不支持来自 Web 应用程序的 CORS 请求.
While all the actual GitHub API endpoints support CORS by sending the right response headers, it is a known issue that the https://github.com/login/oauth/access_token
endpoint for creating an OAuth access token does not support CORS requests from Web applications.
这种情况的非常具体的解决方法是使用 https://github.com/prose/gatekeeper:
The very specific workaround for this case is to use https://github.com/prose/gatekeeper:
Gatekeeper:使客户端应用程序能够与 GitHub 共舞 OAuth.
由于一些与安全相关的限制,Github 阻止您在仅客户端应用程序上实施 OAuth Web 应用程序流程.
Because of some security-related limitations, Github prevents you from implementing the OAuth Web Application Flow on a client-side only application.
这真是太糟糕了.因此,我们构建了 Gatekeeper,这是您使其工作所需的缺失部分.
This is a real bummer. So we built Gatekeeper, which is the missing piece you need in order to make it work.
一般的解决方法是:使用开放的反向代理,例如 https://cors-anywhere.herokuapp.com/
The general workaround is: Use an open reverse proxy like https://cors-anywhere.herokuapp.com/
var req = new XMLHttpRequest();
req.open('POST',
'https://cors-anywhere.herokuapp.com/https://github.com/login/oauth/access_token',
true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send('code=' + encodeURIComponent(location.query.code) +
'&client_id=foo' +
'&client_secret=bar');
...
另请参阅 如何在任何地方使用 Cors 进行反向代理和添加 CORS 标头.
这篇关于github oauth 上的 cors 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!