2014-12-27 40 views
0

我从SO的另一个问题得到了下面的代码。“无法POST /”|卷曲到nodejs(socket.io)

function notifyNode($type, $project_id, $from_user, $data) { 
    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1'); 

    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); 
    curl_setopt($ch, CURLOPT_PORT, 3000); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); 

    curl_setopt($ch, CURLOPT_POST, true); 

    $pf = array('f' => $type, 'pid' => $project_id, 'user_from' => $from_user, 
     'data' => array()); 

    foreach($data as $k => $v) { 
     $pf['data'][$k] = $v; 
    } 

    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($pf)); 

    curl_exec($ch); 
    curl_close($ch); 
} 

$test = array(); 

array_push($test,"first","second","third"); 

notifyNode("test","moretest","user2",$test); 

与我的服务器的NodeJS运行下面的代码:

app.get('/posts', function(req, res){ 

    if(res.socket.remoteAddress == '127.0.0.1') { 
    console.log("connection received"); 
    if(req.method == 'POST') { 

     console.log("POST received"); 
     // The server is trying to send us an activity message 

     var form = new formidable.IncomingForm(); 
     form.parse(req, function(err, fields, files) { 

      res.writeHead(200, [[ "Content-Type", "text/plain"] 
        , ["Content-Length", 0] 
        ]); 
      res.write(''); 
      res.end(); 

      //sys.puts(sys.inspect({fields: fields}, true, 4)); 

      handleServerNotice(fields);     
     }); 
    } 
} 

}); 

不幸的是,当我运行PHP脚本我得到回音消息“无法POST /” ......我跑socket.io监听端口3000,但我不知道这是否是标准程序......任何人都可以帮助我解决这个问题吗?

回答

3

1st)由于app.get,您的API不接受POST请求,您的API在GET requiest上工作,并且您从POST调用它。

2日)这条路线是/职位

curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1'); 

使用它像

curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:3000/posts'); 
+0

你告诉我,我应该有'app.posts( '/帖',函数(REQ,RES) {(...)''而不是get?如果我使用'curl_setopt($ ch,CURLOPT_URL,'http://127.0.0.1:3000/posts');'我可以放弃'curl_setopt($ ch,CURLOPT_PORT, 3000);'? – 2014-12-27 22:26:13

+0

正在执行app.posts(...)'frezees我的页面刷新btw ...奇怪...基本上它“冻结”所有页面请求... – 2014-12-27 22:28:49

+0

app.post(是正确的功能 – 2014-12-28 09:00:20