使PHP将POST卷曲到nodeJS API,但无法读取响应数据

时间:2019-01-27 06:09:37

标签: php node.js curl

我可以成功地执行PHP curl POST到返回返回 来自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的响应中访问submittion_id值

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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