2016-11-10 48 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

相关问题