2017-06-10 35 views
0

$ _POSTデータを処理するphpの機能を持っています。私はカールを使用した後、コンソールに出力<look>Array</look>を表示することができますnodejsを使用してPHPにデータを投稿する方法

if (isset($_POST)) { 
       echo '<look>' . $_POST . '</look>'; 
        exit; 
      } 

:PHPで

curl --data "request=value2" http://localhost/mywebsite/ 

:私はこのように私のデータを送信することができ、カールを使用して

const postData = querystring.stringify({ 
      'request': 'value2' 
     }); 
     // the post options 
     var optionspost = { 
      host: 'localhost', 
      path: 'mywebsite/?request=value2', 
      method : 'POST', 
      port : 80, 
      headers: { 
       'Content-Type': 'application/x-www-form-urlencoded', 
       'Content-Length': Buffer.byteLength(postData) 
      } 
     }; 

     console.info('Options prepared:'); 
     //console.info(optionspost); 
     console.info('Do the POST call'); 


     // do the POST call 
     var reqPost = http.request(optionspost, function(res) { 
      console.log("statusCode: ", res.statusCode); 
      // uncomment it for header details 
      //console.log("headers: ", res); 
      res.on('data', function(d) { 
       console.info('POST result:\n'); 
       console.log(d); 
       var textChunk = d.toString('utf8'); 
       console.log(textChunk); 
       console.info('\n\nPOST completed'); 
      }); 
     }); 

     // write the json data 
     //reqPost.write(jsonObject); 

     reqPost.on('error', function(e) { 
      console.log("post error"); 
      console.error(e); 
     }); 

     reqPost.write(postData); 

     reqPost.end(); 

これが出力されます:

が、どのようにNode.jsの

これは私がこれまで試したものですを使用してPOSTリクエストの上に呼び出すための同じ出力を得るための方法

statusCode: 400 
POST result: 

<Buffer 3c 21 44 4f 43 54 59 50 45 20 48 54 4d 4c 20 50 55 42 4c 49 43 20 22 2d 
2f 2f 49 45 54 46 2f 2f 44 54 44 20 48 54 4d 4c 20 32 2e 30 2f 2f 45 4e 22 3e . 
. > 
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> 
<html><head> 
<title>400 Bad Request</title> 
</head><body> 
<h1>Bad Request</h1> 
<p>Your browser sent a request that this server could not understand.<br /> 
</p> 
<hr> 
<address>Apache/2.4.23 (Win64) PHP/5.6.25 Server at localhost Port 80</address> 
</body></html> 



POST completed 

カールとして。助けてください!

答えて

0

あなたは下の要求モジュールを使用する方法の基本的なコードであることを

ためnpm requestを使用することができ、あなたはそれがより多くの機能を提供するモジュールで見ている必要があります。

var request = require('request'); 
request('http://www.google.com', function (error, response, body) { 
    console.log('error:', error); // Print the error if one occurred 
    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 
    console.log('body:', body); // Print the HTML for the Google homepage. 
}); 

希望これは役立ちます。

0

また、curlコマンドのラッパーであるnode-curlパッケージを試すこともできます。これは、タスクを簡単に実行する方法です。

ここでパッケージをチェックしてください。

https://www.npmjs.com/package/node-curl

は、この情報がお役に立てば幸いです。

関連する問題