简体   繁体   中英

Send JSON from PHP to node.js via cURL

I want to send JSON data from my PHP script to node.js server.

My PHP file looks:

    $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?

    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

hope it helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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