在node.js

时间:2016-02-02 19:20:48

标签: php node.js curl

我在这些SO帖子上尝试了所有示例:

How do I send a POST request with PHP?

PHP cURL Post request not working

总是我的request.body undefined但在请求中我看到"_hasBody":true

我的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);

然后我的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");});

如您所见,在node.js服务器中,我搜索请求我的名字,但控制台说

undefined//no body
-1//could not find your name in the request

然后我将请求移交给响应并将其打印到页面,以便我可以看到整个数据。

从逻辑上讲,我似乎正在将cURL部分作为复制的代码,所以我会说我可能做错了访问变量

我的问题是如何查看请求正文或vars的位置?

1 个答案:

答案 0 :(得分:4)

要处理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回复

{"name":"ben","foo":"bar"}