简体   繁体   English

通过cURL将JSON从PHP发送到node.js

[英]Send JSON from PHP to node.js via cURL

I want to send JSON data from my PHP script to node.js server. 我想将JSON数据从我的PHP脚本发送到node.js服务器。

My PHP file looks: 我的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);

What should I do in node.js? 我应该在node.js中做什么?

    app.all('/push', function(req, res) {
        // what to do here?
    });
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
    });

Your data will be available in req.body 您的数据将在req.body中可用

hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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