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);
});
上面的代码会给我这样的错误
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
最佳答案
虽然所有 the actual GitHub API endpoints support CORS通过发送正确的响应 header ,它是 a known issue用于创建 OAuth 访问 token 的 https://github.com/login/oauth/access_token
端点不支持来自 Web 应用程序的 CORS 请求。
针对这种情况的非常具体的解决方法是使用 https://github.com/prose/gatekeeper :
Gatekeeper: Enables client-side applications to dance OAuth with GitHub.
Because of some security-related limitations, Github prevents you from implementing the OAuth Web Application Flow on a client-side only application.
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/这样的开放式反向代理。
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');
...
另见 How to use Cors anywhere to reverse proxy and add CORS headers .
关于javascript - github oauth 上的 cors 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42150075/