2014-12-27 67 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