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

编程入门 行业动态 更新时间:2024-10-04 05:29:49

使用 PHP <a href=https://www.elefans.com/category/jswz/34/1770198.html style=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 对象的东西。

更多推荐

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

本文发布于:2024-05-30 16:35:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770701.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:cURL   PHP   Node   Post   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!