2016-11-10 44 views
5

我正在開發一個需要https獲取和發佈方法的項目。我有一個短https.get功能在這裏工作......如何在沒有任何第三方模塊的情況下在Node Js中創建https post?

const https = require("https"); 

function get(url, callback) { 
    "use-strict"; 
    https.get(url, function (result) { 
     var dataQueue = "";  
     result.on("data", function (dataBuffer) { 
      dataQueue += dataBuffer; 
     }); 
     result.on("end", function() { 
      callback(dataQueue); 
     }); 
    }); 
} 

get("https://example.com/method", function (data) { 
    // do something with data 
}); 

我的問題是,有沒有https.post,我已經以https模塊How to make an HTTP POST request in node.js?嘗試這裏的HTTP解決方案,但返回控制檯錯誤。

我沒有問題,在我的瀏覽器中使用Ajax獲取和發佈到相同的api。我可以使用https.get發送查詢信息,但我不認爲這是正確的方式,如果我決定展開,我認爲它不會在稍後發送文件。

是否有一個小例子,具有最低要求,使一個https.request什麼是https.post,如果有的話?我不想使用npm模塊。

回答

18

例如,像這樣:

const querystring = require('querystring');                                                 
const https = require('https'); 

var postData = querystring.stringify({ 
    'msg' : 'Hello World!' 
}); 

var options = { 
    hostname: 'posttestserver.com', 
    port: 443, 
    path: '/post.php', 
    method: 'POST', 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded', 
     'Content-Length': postData.length 
    } 
}; 

var req = https.request(options, (res) => { 
    console.log('statusCode:', res.statusCode); 
    console.log('headers:', res.headers); 

    res.on('data', (d) => { 
    process.stdout.write(d); 
    }); 
}); 

req.on('error', (e) => { 
    console.error(e); 
}); 

req.write(postData); 
req.end(); 
+3

尼斯回答@aring。如果您想發送JSON,請更改以下內容: '''Content-Type':'application/json'''' – loonison101

相關問題