使用PHP cURL向Node.js发送Post请求

4

我正在尝试通过PHP cURL向我的node.js服务器发送POST请求,然后向客户端发出消息。服务器已经工作并设置如下:

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , qs = require('querystring')

app.listen(8000);

function handler(req, res) {
    // set up some routes
    switch(req.url) {
        case '/push':

        if (req.method == 'POST') {
            console.log("[200] " + req.method + " to " + req.url);
            var fullBody = '';

            req.on('data', function(chunk) {
                fullBody += chunk.toString();

                if (fullBody.length > 1e6) {
                    // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                    req.connection.destroy();
                }
            });

            req.on('end', function() {              
                // Send the notification!
                var json = qs.stringify(fullBody);
                console.log(json.message);

                io.sockets.emit('push', { message: json.message });

                // empty 200 OK response for now
                res.writeHead(200, "OK", {'Content-Type': 'text/html'});
                res.end();
            });    
        }

        break;

        default:
        // Null
  };
}

我的PHP代码如下:
    $curl = curl_init();
    $data = array('message' => 'simple message!');

    curl_setopt($curl, CURLOPT_URL, "http://localhost:8000/push");
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    curl_exec($curl);

控制台显示 json.message 未定义。为什么会未定义?

为什么不添加console.log(fullBody)以查看正在处理的内容?我怀疑错误是由于body不是您所期望的。 - Hector Correa
谢谢,伙计!问题已经解决了。fullBody 变量现在按预期工作,因此 json 应该实际上等于 qs.parse(fullBody),而不是 qs.stringify(fullBody)。 - Sneaksta
4个回答

2
您正在错误地使用querystring.stringify()。请参阅此处有关querystring方法的文档:http://nodejs.org/docs/v0.4.12/api/querystring.html 我认为您需要的是类似于JSON.stringify()或querystring.parse()的东西,而不是querystring.stringify(),后者是将现有对象序列化为查询字符串的,这与您尝试做的相反。
您需要的是将fullBody字符串转换为JSON对象的东西。

2
如果您的正文只包含JSON blob的字符串版本,则替换


var json = qs.stringify(fullBody);

With

var json = JSON.parse(fullBody);

0
尝试这段代码。
<?php

$data = array(
    'username' => 'tecadmin',
    'password' => '012345678'
);
 
$payload = json_encode($data);
 
// Prepare new cURL resource
$ch = curl_init('https://api.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
 
// Set HTTP Header for POST request 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload))
);
 
// Submit the POST request
$result = curl_exec($ch);
 
// Close cURL session handle
curl_close($ch);

0

对我来说,这是

$data = array(
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'phone' => '1234567890'
);

$json = json_encode($data);
$data = array('simple message!');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($json)
));
$result = curl_exec($ch);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接