2017-01-13 156 views
1

我試圖使用PHP的CURL向我的nodeJS發出請求。 這裏是我的代碼:HTTP從PHP發送到NodeJs服務器的請求

$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); 

但它不起作用。我在數據var中收到了bool(FALSE)。

的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; 
} 

我試着用的NodeJS HTTP-POST和它的作品:

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

它說的是錯的PHP代碼?

PS:CURL包含在PHP中。

回答

0

您的ping函數沒有很好的實現,我認爲。

另外,您需要調用send方法才能發送HTTP響應。

你應該聲明函數是這樣的:

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'); 
} 
+0

謝謝你的答覆,但並不是說。我的webhost限制這個端口上的http-post,使用nodejs工作得很好,因爲它安裝在我的筆記本電腦上,但我的php項目託管,我在88端口更改端口,它工作的很好。謝謝。 –

+0

我很高興知道你解決了你的問題:) –