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);
});
上面的代码会给我这样的错误
我不知道为什么即使我已经在github上注册了oauth应用程序并且回调URL都是
http://127.0.0.1:3000/callback
最佳答案
尽管所有the actual GitHub API endpoints support CORS通过发送正确的响应头而获得,但a known issue表示用于创建OAuth访问 token 的https://github.com/login/oauth/access_token
端点不支持来自Web应用程序的CORS请求。
在这种情况下,非常具体的解决方法是使用https://github.com/prose/gatekeeper:
常规解决方法是:使用像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。