[英]POST to PHP from Node.js
我試圖將Node.js應用程序中的一些數據發布到PHP腳本。 暫時我只是構建一個概念證明,但我無法將實際數據傳遞給PHP端。 請求通過,我得到200回來,但PHP認為$ _POST數組是空的。
這是我的節點代碼:
// simple end point just for testing
exports.testPost = function(request, response) {
data = request.body.data;
postToPHP(data);
response.end(data);
}
function postToPHP (data) {
var http = require('http');
var options = {
host : 'localhost',
port : 8050,
path : '/machines/test/index.php',
method : 'POST',
headers : {
'Content-Type' : 'application/json',
'Content-Length' : Buffer.byteLength(data)
}
};
var buffer = "";
var reqPost = http.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function(d) {
console.info('POST Result:\n');
//process.stdout.write(d);
buffer = buffer+data;
console.info('\n\nPOST completed');
});
res.on('end', function() {
console.log(buffer);
});
});
console.log("before write: "+data);
reqPost.write(data);
reqPost.end();
}
同樣,請求進入localhost:8050 / machines / test / index.php,但當我執行$ _POST的var_dump時,它是一個空數組。
[29-Jan-2014 21:12:44] array(0) {
}
我懷疑我在使用.write()方法做錯了但是我無法弄清楚是什么。 任何關於我遺失或做錯的輸入都將非常感激。
*更新:
有些評論表明使用了file_get_contents('php:// input'); 確實可以在PHP端獲取數據,但我仍然希望能夠直接訪問$ _POST數組。
由於你使用Content-Type: application/json
發送數據,你需要讀取原始輸入,因為php不知道如何將json讀入他們的全局變量,如_GET和_POST,除非你有一些php擴展來完成它。
您可以使用查詢字符串庫將對象解析為名稱 - 值對查詢字符串,您可以使用Content-Type:application/x-www-form-urlencoded
進行傳輸,以便將數據解析為全局變量
var data = {
var1:"something",
var2:"something else"
};
var querystring = require("querystring");
var qs = querystring.stringify(data);
var qslength = qs.length;
var options = {
hostname: "example.com",
port: 80,
path: "some.php",
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': qslength
}
};
var buffer = "";
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
buffer+=chunk;
});
res.on('end', function() {
console.log(buffer);
});
});
req.write(qs);
req.end();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.