“Cannot POST /” | curl to nodejs (socket.io)

2019-08-10 22:33发布

I got the following code from another question here in SO.

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

with my nodejs server running the following code:

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);                
        });
    }
}

});

Unfortunately, when I run the php script I get an echo message "Cannot POST /"... I'm running socket.io listening in port 3000, but I don't know if this is the standard procedure... Can anyone help me in this one?

标签: php node.js curl
1条回答
相关推荐>>
2楼-- · 2019-08-10 23:02

1st ) Your API is not accepting POST request because of app.get, You API is work on GET requiest and you are calling it from POST.

2nd) The route is /posts

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

use it like

  curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:3000/posts');
查看更多
登录 后发表回答