아래 코드는 Node.js 에서 HTTP요청을 Basic authentication 인증과 함께 진행하는 예제입니다.
1. POST 방식입니다.
var http = require('http');
var useridpw = "myid:mypasswd";
var value = "#$!@%#@!%@!^&&-==";
var data = "myvalue=" + encodeURIComponent(value);
var options = {
host: 'gunman.com',
path: '/api/2.0',
auth: useridpw,
type: "post",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var request = http.request(options,
function (response) {
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('RESULT: ' + chunk);
});
});
request.write(data);
request.end();2. HTTPS 로 요청하는 예제입니다.
//https 를 사용합니다.
var https = require('https');
var useridpw = "myid:mypasswd";
var value = "#$!@%#@!%@!^&&-==";
var data = "myvalue=" + encodeURIComponent(value);
var options = {
host: 'gunman.com',
path: '/api/2.0',
port: 443, //443포트를 주로 사용합니다.
auth: useridpw,
type: "post",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var request = https.request(options,
function (response) {
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('RESULT: ' + chunk);
});
});
request.write(data);
request.end();