簡體   English   中英

使用 PHP cURL 向 Node.js 發送 Post 請求

[英]Send Post request to Node.js with PHP cURL

我正在嘗試通過 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 未定義。 為什么是未定義的?

您使用的 querystring.stringify() 不正確。 在此處查看有關查詢字符串方法的文檔:

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

我相信你想要的是 JSON.stringify() 或 querystring.parse(),而不是 querystring.stringify(),它應該將現有對象序列化為查詢字符串; 這與您正在嘗試做的相反。

您想要的是將您的 fullBody 字符串轉換為 JSON 對象的東西。

如果您的正文僅包含 JSON blob 的字符串化版本,則替換

var json = qs.stringify(fullBody);

var json = JSON.parse(fullBody);

試試這個代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM