简体   繁体   中英

How to convert curl request to javascript

I'm trying to send an HTTP request from my react code to iphub API.

in the document there is an example of how to use in this service:

curl http://v2.api.iphub.info/ip/8.8.8.8 -H "X-Key: 123"

I convert the request according to some answers and it looks like this:

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
  }),
})

but the response is 404, I think that my request is wrong, how can I know if the converted request correct?

You are mixing up response and request headers.

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. Response headers, like Age , Location or Server are used to give a more detailed context of the response. ... However, these entity requests are usually called responses headers in such a context.

Source: 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. Request headers, like Accept , Accept-* , or If-* allow to perform conditional requests; others like Cookie , User-Agent or Referer precise the context so that the server can tailor the answer.

Source: https://developer.mozilla.org/en-US/docs/Glossary/Request_header

For a simple GET request, you usually do not need any header at all, see HTTP GET request in JavaScript? In your case, in you curl command, you specified a single additional header, and so you might just do that in Javascript as well.

Try this out:

<?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);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM