简体   繁体   中英

HTTP Post request from PHP to NodeJs Server

I tried to make a request to my nodeJS using CURL from PHP. Here is my code:

$host = 'http://my_ip:8080/ping';
$json = '{"id":"13"}';

$ch = curl_init($host);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($json))
    );
$data = curl_exec($ch);
var_dump($data);

But it doesn't work. I received bool(FALSE) in data var.

NodeJS:

app.use(router(app));
app.post('/ping', bodyParser, ping);
port = 8080;
app.listen(port, webStatus(+port));
function* ping() {
    console.log(this.request.body);
    this.body = 1;
}

I tried with NodeJS Http-post and it works:

http.post = require('http-post');
http.post('http://my_ip:8080/ping', { id: '13' }, function (res) {
    res.on('data', function (chunk) {
        console.log(chunk);
    });
});

Is it something wrong with PHP code?

PS: The CURL is included in PHP.

Your ping function is not well implemented I think.

Also, you need to call the send method in order to send the HTTP response.

You should declare the function like this :

app.use(bodyParser); // You can use a middleware like this too.

app.post('/ping', ping);

function ping (req, res) {
    console.log(req.body); // Since you use `bodyParser` middleware, you can get the `body` directly.

    // Do your stuff here.

    res.status(200).send('toto');
}

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