Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/479.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 使用带有API密钥头的获取API_Javascript_React Native_Http Headers_Fetch Api - Fatal编程技术网

Javascript 使用带有API密钥头的获取API

Javascript 使用带有API密钥头的获取API,javascript,react-native,http-headers,fetch-api,Javascript,React Native,Http Headers,Fetch Api,我们如何配置获取API以包含API密钥头 我已经创建了一个API,通过在标题中包含API键,我可以成功地接收来自POSTMAN或Fiddler的响应 但是,从我的代码(React/javascript)中使用以下代码段失败 return fetch(url) .then(response => response.json(),{ mode: 'cors', headers: { 'x-api-key': '5

我们如何配置获取API以包含API密钥头

我已经创建了一个API,通过在标题中包含API键,我可以成功地接收来自POSTMAN或Fiddler的响应

但是,从我的代码(React/javascript)中使用以下代码段失败

        return fetch(url)
      .then(response => response.json(),{
        mode: 'cors', 
        headers: {
          'x-api-key': '5485748746547e847483983343433243',
          'User-Agent' : 'My-App',
          'Accept': '*/*',
        },
      })
      .catch(error => console.log('Error while fetching:', error))
在《邮递员》中,我可以删除除x-api-key之外的所有标题,效果很好。在我的代码中似乎没有标题或配置的组合

如果我在Fiddler中捕获该请求,则Fetch请求未添加x-api-key头


配置fetch以发送api密钥头的正确方法是什么?

您的选项位于错误的位置。它们应该位于fetch函数的第二个参数中

返回获取(url{
模式:“cors”,
标题:{
“x-api-key”:“5485748746547E84748398334343243”,
“用户代理”:“我的应用程序”,
“接受”:“*/*”,
},
})
.then(response=>response.json())
.catch(错误=>console.log('获取时出错:',错误))

谢谢-我没有注意到我将代码复制到了错误的行中。感谢您的代码审查!