Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 尝试访问Spotify API时未定义json_Javascript_Json_Reactjs_Authentication_Ecmascript 6 - Fatal编程技术网

Javascript 尝试访问Spotify API时未定义json

Javascript 尝试访问Spotify API时未定义json,javascript,json,reactjs,authentication,ecmascript-6,Javascript,Json,Reactjs,Authentication,Ecmascript 6,我正在尝试使用Spotify API中的客户端凭据流获取访问令牌。我有以下代码 let oAuthOptions = { url: 'https://accounts.spotify.com/api/token', method: 'POST', headers: { 'Authorization' : 'Basic ' + btoa(CLIENT_ID+':'+CLIENT_SECRET) }, grant_type: 'client_credentials',

我正在尝试使用Spotify API中的客户端凭据流获取访问令牌。我有以下代码

let oAuthOptions = {
  url: 'https://accounts.spotify.com/api/token',
  method: 'POST',
  headers: {
    'Authorization' : 'Basic ' + btoa(CLIENT_ID+':'+CLIENT_SECRET)
  },
  grant_type: 'client_credentials',
  redirect_uri: 'http://localhost:8888/callback ',
};

fetch(oAuthOptions)
  .then(response => response.json())
  .then(response => {
      console.log(response)  
});
我得到了一个未定义的json,我不知道为什么,ID和客户机机密是可以的,因为我已经用编码基尝试了curl,它工作了。 我尝试使用response.body.json(),但它报告了一个错误response.body.json不是一个函数

尝试向承诺添加一个捕获(错误),以检查发生了什么:

fetch(url, oAuthOptions)
  .then(response => response.json())
  .then(response => {
      console.log(response)  
   })
  .catch(e => console.log("Error:", e));
如果错误为“SyntaxError:Unexpected token<在JSON中的位置0”,则响应不是JSON有效数据。在这种情况下,请尝试返回
response.text()
以查看纯文本响应:

fetch(url, oAuthOptions)
  .then(response => response.text())
  .then(response => {
      console.log(response)
   })
在您的情况下,URL是
https://accounts.spotify.com/api/token
。看起来响应没有CORS策略,因此如果您从网站中的未知主机调用此响应,它将被阻止


响应对象是什么样子的?也许它需要JSON.parse?body:ReadableStream{locked:false}​ bodyUsed:假​ 标题:标题{}​ 好的,没错​ 重定向:错误​ 现状:200​ 状态文本:“确定”​ 类型:“基本”​ 网址:“​ : ResponsePrototype{clone:clone(),arrayBuffer:arrayBuffer(),blob:blob(),…}最后的输出看起来像原始响应对象,而不是response.json()结果(),是的,因为@hurnhu请求响应对象本身,但如果我请求response.json()的话我得到了这个错误:JSON.parse:JSON数据的第1行第1列出现意外字符这是同一个错误:error:SyntaxError:“JSON.parse:JSON数据的第1行第1列出现意外字符”。使用text()返回我的react appOk的html,您可以检查
response.text()
输出吗?看起来响应不是JSONYes。这是我的react应用程序的html。因此,您需要在
fetch(URL,config)
调用中设置URL,而不是配置。实际上,它是在调用你自己的站点,而不是我尝试过的,但它给了我一个CORS错误,我不知道如何解决,但我下载了一个firefox插件,它一直报告相同的json错误。