php - 从 PHP 到 NodeJs 服务器的 HTTP Post 请求

标签 php node.js post http-post

我尝试使用 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 中。

最佳答案

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

关于php - 从 PHP 到 NodeJs 服务器的 HTTP Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41633153/

相关文章:

php - 如何将带逗号的字符串插入MYSQL

node.js - TypeError : Object {. ..} 没有方法 'find' - 当将 mongoose 与express一起使用时

node.js - CMD 终止服务器上的 Node JS

python - 如何使用 Python Requests 模块模拟 HTTP 发布请求?

php - 为包括外键在内的整个模式转储 MySQL CREATE TABLE(创建顺序)

php - htmlspecialchars 不允许换行?

php - Ajax 条件响应不起作用

node.js - Node Redis : How to filter a sorted set of keys and retrieve each keys hashed values in one call

php - 确定功能是否设置的正确方法

javascript - 处理响应数据 PHP