【问题标题】:HTTP Post request from PHP to NodeJs Server从 PHP 到 NodeJs 服务器的 HTTP Post 请求
【发布时间】:2017-01-13 11:05:14
【问题描述】:

我尝试使用 PHP 中的 CURL 向我的 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);

但它不起作用。我在数据变量中收到 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 中。

【问题讨论】:

    标签: php node.js post http-post


    【解决方案1】:

    我认为您的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');
    }
    

    【讨论】:

    • 感谢您的回复,但事实并非如此。我的网络主机在此端口上限制 http-post,nodejs 运行良好,因为安装在我的笔记本电脑上,但我的 php 项目是托管的,我在 88 中更改端口并且运行良好。谢谢。
    • 很高兴知道您解决了问题 :)
    猜你喜欢
    • 2015-09-01
    • 2014-09-02
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    相关资源
    最近更新 更多