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

7dl7o3gd  于 2023-05-05  发布在  PHP
关注(0)|答案(4)|浏览(209)

我试图通过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是undefined。为什么是undefined?

t3psigkw

t3psigkw1#

您使用querystring.stringify()不正确。在这里查看querystring方法的文档:
http://nodejs.org/docs/v0.4.12/api/querystring.html
我相信你想要的是类似JSON.stringify()或querystring.parse()的东西,而不是querystring.stringify(),后者应该将现有对象序列化为查询字符串;这和你想做的正好相反
您需要的是将fullBody字符串转换为JSON对象的东西。

nwnhqdif

nwnhqdif2#

如果您的body仅包含JSON blob的字符串化版本,则替换

var json = qs.stringify(fullBody);

var json = JSON.parse(fullBody);
ghg1uchk

ghg1uchk3#

试试这个代码

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

efzxgjgh4#

对我来说是的

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

相关问题