最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin29浏览0评论

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

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

我正在尝试通过 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 未定义。为什么它是未定义的?

回答如下:

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

http://nodejs/docs/v0.4.12/api/querystring.html

我相信你想要的是像 JSON.stringify() 或 querystring.parse() 这样的东西,而不是应该将现有对象序列化为查询字符串的 querystring.stringify();这与你想要做的相反。

你想要的是将你的 fullBody 字符串转换成 JSON 对象的东西。

发布评论

评论列表(0)

  1. 暂无评论