[英]PHP cURL request body is undefined in node.js
I've tried all the examples on these SO posts: 我已经尝试过这些SO帖子中的所有示例:
How do I send a POST request with PHP? 如何使用PHP发送POST请求?
PHP cURL Post request not working PHP cURL发布请求不起作用
Always my request.body is undefined
yet in the request itself I see "_hasBody":true
总是我的request.body是
undefined
但在请求本身中却看到"_hasBody":true
The current code for my php post file: 我的php发布文件的当前代码:
function httpPost($url,$data){
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,http_build_query($data));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
$response=curl_exec($curl);
curl_close($curl);
return $response;
}
$fields = array(
'name' => 'ben'
, 'foo' => 'bar'
);
echo httpPost("http://localhost:8002", $fields);
Then my node.js listening server code is: 然后我的node.js侦听服务器代码是:
var test=require('http').createServer(function(q,a){//question,answer
console.log(q.body);
console.log(JSON.stringify(q).indexOf('ben'));
a.end(JSON.stringify(q));
});
test.listen(8002,function(e,r){console.log("listening");});
As you can see, in the node.js server I search the request for my name but the console says 如您所见,在node.js服务器中,我在请求中搜索了我的名字,但控制台显示
undefined//no body
-1//could not find your name in the request
then I hand over the request back to the response and print it to the page so I can see the whole data. 然后将请求移交给响应,并将其打印到页面上,这样我就可以看到整个数据。
logically it would seem that I am doing the cURL part right as its copied code , so I would say I might be doing something wrong to access the vars 从逻辑上看,我似乎正确地将cURL部分作为其复制的代码 ,所以我会说我在访问var时可能做错了什么
My question is how do I see the request body or where the vars? 我的问题是如何查看请求正文或var在哪里?
To handle a POST request, you have to do the following: 要处理POST请求,您必须执行以下操作:
var qs = require('querystring');
var http = require('http');
var test = http.createServer(function(req, res) {
//Handle POST Request
if (req.method == 'POST') {
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function() {
var POST = qs.parse(body);
console.log(body); // 'name=ben&foo=bar'
console.log(POST); // { name: 'ben', foo: 'bar' }
if(POST.name == 'ben')
console.log("I'm ben"); //Do whatever you want.
res.setHeader("Content-Type", "application/json;charset=utf-8");
res.statusCode = 200;
res.end(JSON.stringify(POST)); //your response
});
}
});
test.listen(8002, function(e, r) {
console.log("listening");
});
cURL response : cURL响应 :
{"name":"ben","foo":"bar"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.