【问题标题】:Made PHP curl POST to nodeJS API but can't read response data使 PHP curl POST 到 nodeJS API 但无法读取响应数据
【发布时间】:2019-01-27 06:09:37
【问题描述】:

我可以成功地向 NodeJS API 执行 PHP curl POST,该 API 返回一个 来自 NodeJS 的响应

res.json({status:'ok',submission_id:id});

但我无法正确解析响应,这将返回 NULL

// $newRequired = a complete array
$host = 'https://URL_HERE';
$json = json_encode($newRequired);

$ch = curl_init($host);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Accept: application/json',
        'Content-Length: ' . strlen($json))
);
$response = curl_exec($ch);
$var = json_decode($response, true);
var_dump($var);

如果我只是 echo $response 到页面的响应如下所示

HTTP/1.1 200 OK
Server: nginx/1.10.3 (Ubuntu)
Date: Sun, 27 Jan 2019 05:55:30 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 34
Connection: keep-alive
X-Powered-By: Express
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
ETag: W/"XXXXXXX"

{"status":"ok","submission_id":83}

我想从 PHP 的响应中访问 submit_id 值

【问题讨论】:

    标签: php node.js curl


    【解决方案1】:

    我找到了我的问题的解决方案。我必须确保 NodeJS API 不会通过添加此选项来返回标头curl_setopt($ch, CURLOPT_HEADER, false); 之后我才能解析数据。

    【讨论】:

      【解决方案2】:

      尝试在curl_close($ch);之前关闭curl

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-17
        • 1970-01-01
        • 2016-01-09
        • 1970-01-01
        • 2019-08-15
        • 2023-01-29
        • 2015-05-21
        相关资源
        最近更新 更多