[英]How to convert curl request to javascript
我正在嘗試從我的反應代碼向 iphub API 發送 HTTP 請求。
在文檔中有一個如何在此服務中使用的示例:
curl http://v2.api.iphub.info/ip/8.8.8.8 -H "X-Key: 123"
我根據一些答案轉換了請求,它看起來像這樣:
const ripeEndpoint = 'http://v2.api.iphub.info/ip/8.8.8.8'
fetch(ripeEndpoint, {
method: 'GET',
headers: new Headers({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'multipart/form-data',
'X-Key': myApiKey
}),
})
但是響應是404,我認為我的請求是錯誤的,我怎么知道轉換后的請求是否正確?
您正在混淆響應和請求標頭。
A response header is an HTTP header that can be used in an HTTP response and that doesn't relate to the content of the message. 響應標頭,例如
Age
、Location
或Server
用於提供更詳細的響應上下文。 ...但是,在這種情況下,這些實體請求通常稱為響應標頭。
資料來源: https://developer.mozilla.org/en-US/docs/Glossary/Response_header
A request header is an HTTP header that can be used in an HTTP request, and that doesn't relate to the content of the message. 請求標頭,如
Accept
、Accept-*
或If-*
允許執行條件請求; 其他類似Cookie
、User-Agent
或Referer
的工具可以精確上下文,以便服務器可以定制答案。
來源: https://developer.mozilla.org/en-US/docs/Glossary/Request_header
對於一個簡單的GET
請求,您通常根本不需要任何 header,請參閱JavaScript 中的 HTTP GET 請求? 在您的情況下,在您的curl
命令中,您指定了一個額外的 header,因此您也可以在 Javascript 中執行此操作。
試試這個:
<?php
$ipaddress = $_SERVER['REMOTE_ADDR'];
$url = 'http://v2.api.iphub.info/ip/'.$ipaddress;
$auth = "OTf4sfpNHUhRM1AwNVMOZlJPSmRseTY0WTFsMGhtR1J0alhEbW==";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-Key: {$auth}"]);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.