将 Axios GET 请求转换为 PHP cURL
Converting an Axios GET Request to PHP cURL
我有一个要转换为 PHP cURL 的 Axios HTTP GET 请求。
Axios 请求
axios({
method: 'get',
url: 'https://api.sample.com/123456789/',
data: {
apikey: '987654321',
id: '123123',
}
}).then(function ( response ) {
console.log( response );
});
如何在 PHP cURL 中发出此请求,发送 apikey 和 id 数据,然后回应响应?
我正在尝试的 cURL
<?php
$url = 'https://api.sample.com/123456789/';
$body_arr = [
'apikey' => '987654321',
'id' => '123123',
];
$data = http_build_query($body_arr);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result_arr = json_decode($result, true);
echo '<pre>';
var_dump( $result_arr );
echo '</pre>';
?>
结果
NULL
当您与 method: 'GET'
一起设置数据时,axios 将设置 Content-Type: application/json
并且..完全忽略 post 数据。所以正确的翻译是:
<?php
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://api.sample.com/123456789/',
CURLOPT_HTTPGET => 1,
CURLOPT_HTTPHEADER => array(
// this is not correct, there is no content-type,
// but to mimic Axios's behavior with setting `data` on GET requests, we send this
// incorrect header:
'Content-Type: application/json'
)
));
curl_exec($ch);
- fwiw 这感觉像是一个 axios 错误,如果这在 axios 的未来版本中发生变化,我不会感到惊讶。
我有一个要转换为 PHP cURL 的 Axios HTTP GET 请求。
Axios 请求
axios({
method: 'get',
url: 'https://api.sample.com/123456789/',
data: {
apikey: '987654321',
id: '123123',
}
}).then(function ( response ) {
console.log( response );
});
如何在 PHP cURL 中发出此请求,发送 apikey 和 id 数据,然后回应响应?
我正在尝试的 cURL
<?php
$url = 'https://api.sample.com/123456789/';
$body_arr = [
'apikey' => '987654321',
'id' => '123123',
];
$data = http_build_query($body_arr);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result_arr = json_decode($result, true);
echo '<pre>';
var_dump( $result_arr );
echo '</pre>';
?>
结果
NULL
当您与 method: 'GET'
一起设置数据时,axios 将设置 Content-Type: application/json
并且..完全忽略 post 数据。所以正确的翻译是:
<?php
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://api.sample.com/123456789/',
CURLOPT_HTTPGET => 1,
CURLOPT_HTTPHEADER => array(
// this is not correct, there is no content-type,
// but to mimic Axios's behavior with setting `data` on GET requests, we send this
// incorrect header:
'Content-Type: application/json'
)
));
curl_exec($ch);
- fwiw 这感觉像是一个 axios 错误,如果这在 axios 的未来版本中发生变化,我不会感到惊讶。