1. 程式人生 > >nodejs中http協議的客戶端請求

nodejs中http協議的客戶端請求

nodejs中客戶端請求主要兩種方式get和post
get例子
var http = require('http');
http.get("http://10.10.10.10/index.html?key=aaadd222&crytoResult=2232jjfrkkkkkk", function(res) { 
    console.log("Got response: " + res.statusCode); 
    }).on('error', function(e) { 
    console.log("Got error: " + e.message); 
   req.on('data',(data)=>{//接收來自伺服器返回的資料
console.log(data.toString('utf-8'));
});
});


post例子
var http = require('http');
var contents  =  querystring.stringify({
    'cipherResult':'getk2kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkKey',
    'cipherResult2':'getkkkkk2kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkKey'
});
var options={
host:'10.10.10.1',
path:'/',
port:8888,
method:'POST',
headers:{
'Content-Type':'application/x-www-form-urlencoded',
                'Content-Length':contents.length
}
};


 var req = http.request(options,(res) =>{
res.on('data',(data) => {
console.log(data.toString('utf8'));
});
});
req.write(client_key);
req.end();