【问题标题】:Send Post request to Node.js with PHP cURL使用 PHP cURL 向 Node.js 发送 Post 请求
【发布时间】:2012-08-31 20:36:48
【问题描述】:

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

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) 来看看你在处理什么?我怀疑错误是身体不是你所期望的。
  • 谢谢伙计!刚刚解决了问题。 fullBody var 现在按预期工作,因此 json 实际上应该 = qs.parse(fullBody),而不是 qs.stringify(fullBody)。

标签: php node.js curl


【解决方案1】:

您错误地使用了 querystring.stringify()。在此处查看有关查询字符串方法的文档:

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

    var json = JSON.parse(fullBody);
    

    【讨论】:

      【解决方案3】:

      试试这个代码

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-08
        • 2014-11-06
        • 1970-01-01
        • 2017-05-03
        • 1970-01-01
        • 1970-01-01
        • 2018-09-06
        相关资源
        最近更新 更多