【问题标题】:Send JSON from PHP to node.js via cURL通过 cURL 将 JSON 从 PHP 发送到 node.js
【发布时间】:2016-03-24 12:22:38
【问题描述】:

我想将 JSON 数据从我的 PHP 脚本发送到 node.js 服务器。

我的 PHP 文件看起来:

    $data = array("name" => "Lorerm", "age" => "18");                                                                    
    $data_string = json_encode($data);                                                                                   

    $ch = curl_init('http://localhost:3000/push');                                                                      
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_string))                                                                 
    );
    curl_exec($ch);

在 node.js 中我应该做什么?

    app.all('/push', function(req, res) {
        // what to do here?
    });

【问题讨论】:

  • 通过console.log(res)console.log(req)检查数据是否发布
  • @C0dekid.php req/res 上没有我的数据。

标签: php node.js curl


【解决方案1】:
app.all('/push', function(req, res) {
        console.log(req.body.name); // Lorem
        console.log(req.body.name); // 18
        res.status(200).json({data:req.body); // will give { name: 'Lorem',age:18'} in response
    });

您的数据将在 req.body 中可用

希望对你有帮助:)

【讨论】:

  • 你是否在 node.js 服务器中添加了正文解析器?
  • 我有'var bodyParser = require('body-parser')'。
  • 把 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false}));之后
  • 啊,现在可以了。你太棒了,谢谢你的工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 2013-02-05
  • 2019-07-23
  • 2016-07-03
  • 1970-01-01
  • 2018-06-22
  • 2017-04-23
相关资源
最近更新 更多