我正在尝试向 API 发送 GET 请求,但是当我在代码中添加自定义标头时,会发生一些奇怪的事情。
当请求方法到达 Web 服务器时,某个地方会更改为 OPTIONS。
但是当我在没有标头的情况下执行相同操作时,它将是 GET 类型。
当我使用应用程序邮递员(API 开发工具)时,请求工作正常!
请求代码:
let token = this.generateClientToken(privateKey, message);
let myheaders = {
"appID": appID,
"authorizationkey": token
}
fetch('http://localhost:8080/api/app/postman', {
method: "GET",
// body: JSON.stringify(''),
headers: myheaders
}).then(function(response) {
console.log(response.status); //=> number 100–599
console.log(response.statusText); //=> String
console.log(response.headers); //=> Headers
console.log(response.url); //=> String
return response.text()
}, function(error) {
console.log(error.message); //=> String
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
服务器日志输出(带标题):
worker_1 | 172.18.0.4 - 17/Mar/2017:15:47:44 +0000 "OPTIONS /index.php" 403
web_1 | 172.18.0.1 - - [17/Mar/2017:15:47:44 +0000] "OPTIONS /api/app/postman HTTP/1.1" 403 5 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0" "-"
服务器日志输出(不带标题):
worker_1 | 172.18.0.4 - 17/Mar/2017:16:01:49 +0000 "GET /index.php" 403
web_1 | 172.18.0.1 - - [17/Mar/2017:16:01:49 +0000] "GET /api/app/postman HTTP/1.1" 403 5 "http://localhost:3000/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0" "-"
添加了 NPM 模块以在额外的浏览器中提供获取支持:
https://github.com/github/fetch#obtaining-the-response-url
https://github.com/taylorhakes/promise-polyfill
我在这里缺少什么?在我看来这一切都是正确的。
我正在使用 Firefox 开发版通过 NPM start 运行它来测试 Reactjs 应用程序
接受的答案游戏我的解决方案,我没有使用nodeJS后端,而是使用带有php-fpm的普通Nginx。
但答案解释了带有自定义标头的请求如何总是首先执行 OPTIONS 请求来验证是否接受设置的标头名称,因此我必须更改网络服务器中的响应以返回包含正确标头的 204 代码。
如果没有它,我的 PHP 代码中身份验证将失败并导致 403 代码,因为缺少包含内容和所使用的请求方法的标头。
这是我添加到 Nginx 主机以使其正常工作的内容:
location ~ \.php$ {
add_header 'Access-Control-Allow-Origin' "*";
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
add_header 'Access-Control-Allow-Headers' 'appID,authorizationkey';
if ($request_method = 'OPTIONS') {
return 204;
}
}
我知道它远非完美,但目前它已经可以工作了。再次感谢您为我指明了正确的方向。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)