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