Javascript 从POST in fetch请求到Github API的读取结果出现问题
我正在使用fetchapi获取从githubapi返回的访问令牌 当我检查网络选项卡时,我看到令牌已返回,但我无法在我的Javascript 从POST in fetch请求到Github API的读取结果出现问题,javascript,reactjs,fetch,github-api,Javascript,Reactjs,Fetch,Github Api,我正在使用fetchapi获取从githubapi返回的访问令牌 当我检查网络选项卡时,我看到令牌已返回,但我无法在我的fetch请求中访问它 我的代码如下所示: fetch(`https://github.com/login/oauth/access_token?client_id=***&client_secret=***&code=${code}&redirect_uri=http://localhost:3000/&state=react`, {
fetch
请求中访问它
我的代码如下所示:
fetch(`https://github.com/login/oauth/access_token?client_id=***&client_secret=***&code=${code}&redirect_uri=http://localhost:3000/&state=react`, {
method: 'POST',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(function(res) {
console.log(res); // I have already tried return res.json() here
})
如果我返回res.json()
,控制台将显示以下错误:
index.js:30未捕获(承诺中)语法错误:输入意外结束
声明响应采用以下格式:
默认情况下,响应采用以下形式:
access_-token=E72E16C7E42F2922C6912E7710C8347AE178B4A&token_-type=bearer
我猜它没有返回有效的json,只是返回一个字符串,所以我不确定如何访问这个响应
响应如下所示:
fetch(`https://github.com/login/oauth/access_token?client_id=***&client_secret=***&code=${code}&redirect_uri=http://localhost:3000/&state=react`, {
method: 'POST',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(function(res) {
console.log(res); // I have already tried return res.json() here
})
但是,当我尝试注销响应时,我得到
语法错误:输入意外结束
如果您使用模式:“无cors
,浏览器将限制访问正文。浏览器具有跨域安全性。如果您想访问body,则必须在不使用模式的情况下调用:'no cors
属性
这会奏效的
这行不通
我想你快到了。你已经向医生提到了。如果您进一步阅读,您可以看到要获得JSON响应,您需要包含一个名为
Accept
的标题,其值为application/JSON
fetch(` ... `, {
method: 'POST',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json'
})
}).then(function(res) {
...
})
通过这种方式,您可以在
res
上应用.json()
,您可以检查res
是否是有效的json吗?为了节省您的时间,请将此留在这里:我一直在使用控制台。如果您阅读了问题,我已经在控制台中显示了错误,因此您有2个,但我只看到1个承诺。。是的,您在控制台中看到错误,但您没有调试。。断点?@31piy我不认为它是有效的,儿子,但我不确定如何得到响应-更新的问题,参考GitHub Docs我需要使用模式:无cors
来允许请求是否有任何特定的原因使用无cors
。如果github通过跨域限制您,您必须删除no cors
,并创建您自己的后端api,从github获取数据。我正在获取返回的响应,但无法在fetch requestYes中访问它。浏览器将接受响应,但不会将访问JavaScript作为安全策略。
fetch(` ... `, {
method: 'POST',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json'
})
}).then(function(res) {
...
})