【问题标题】:"Cannot POST /" | curl to nodejs (socket.io)“无法发布 /” |卷曲到 nodejs (socket.io)
【发布时间】:2014-12-27 20:01:55
【问题描述】:

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

我的 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 上监听,但我不知道是否这是标准程序...有人可以帮我吗?

【问题讨论】:

    标签: php node.js curl


    【解决方案1】:

    1st ) 由于 app.get,您的 API 不接受 POST 请求,您的 API 正在处理 GET 请求,而您正在从 POST 调用它。

    2nd) 路由是 /posts

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

    像这样使用它

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

    【讨论】:

    • 你是在告诉我我应该有app.posts('/posts', function(req, res){ (...)而不是get?如果我使用curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:3000/posts');,我可以丢弃curl_setopt($ch, CURLOPT_PORT, 3000);吗?
    • app.posts(...) 冻结我的页面刷新顺便说一句...奇怪...基本上它“冻结”所有页面请求...
    猜你喜欢
    • 2018-10-27
    • 2017-03-05
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多