Taw*_*man 9 javascript github xmlhttprequest cors
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);
});Run Code Online (Sandbox Code Playgroud)
上面的代码会给我一个这样的错误
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 "访问.
我不知道为什么即使我已经使用github和回调网址注册了oauth应用程序 http://127.0.0.1:3000/callback
虽然所有实际的GitHub API端点都通过发送正确的响应标头来支持CORS,但是已知的问题是https://github.com/login/oauth/access_token创建OAuth访问令牌的端点不支持来自Web应用程序的CORS请求.
这种情况的具体解决方法是使用https://github.com/prose/gatekeeper:
Gatekeeper:允许客户端应用程序与GitHub共舞OAuth.
由于一些与安全相关的限制,Github阻止您在仅客户端的应用程序上实现OAuth Web应用程序流.
这是一个真正的无赖.因此我们构建了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');
...
Run Code Online (Sandbox Code Playgroud)
另请参阅如何在任何地方使用Cors来反向代理并添加CORS标头.