2016-11-10 23 views
5

Pracuję nad projektem, który wymaga metod https get i post. Mam krótkie funkcję https.get pracuje tutaj ...Jak utworzyć post https w węźle Node Js bez modułu zewnętrznego?

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 
}); 

Moim problemem jest to, że nie ma https.post a ja już próbowałem tutaj http rozwiązanie z modułem https How to make an HTTP POST request in node.js? ale zwraca błędy konsoli.

Nie miałem problemu z używaniem funkcji pobierania i publikowania z Ajaxem w mojej przeglądarce do tego samego interfejsu API. Mogę użyć https.get do wysyłania informacji o zapytaniach, ale nie sądzę, że byłby to poprawny sposób i nie sądzę, że będzie działało wysyłanie plików później, jeśli zdecyduję się rozwinąć.

Czy istnieje mały przykład, z minimalnymi wymaganiami, aby https.request byłby https.post, gdyby taki był? Nie chcę używać modułów npm.

Odpowiedz

18

Na przykład coś takiego:

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

Nicea odpowiedź @aring. Jeśli chcesz wysłać JSON, zmień: '' 'var postData = JSON.stringify ({msg: 'Hello World!'})' '' i '' ''Content-Type': 'application/json'''' – loonison101

Powiązane problemy