기본 HTTP 요청하기
var http = require('http');
var options = {
hostname: 'httpbin.org',
path: '/ip'
};
function handleResponse(response) {
var serverData = '';
response.on('data', function (chunk) {
serverData += chunk;
});
response.on('end', function () {
console.log("received server data:");
console.log(serverData);
});
}
http.request(options, function(response){
handleResponse(response);
}).end();
참고 사항
- 접속 옵션 지정시, URL 중 호스트명은 hostname에, 세부 하위 경로는 path에 들어간다.
- https 접속을 하려면, http 모듈 대신에 https 모듈을 사용하면 된다.
var http = require("https");
- 특정 포트 지정시는 아래와 같이 추가한다.
var options = {
...
port: '4242'
};
POST 요청하기
var http = require("http");
var options = {
hostname: 'httpbin.org',
path: '/post',
method: 'POST',
headers: {
'Content-Type': 'text/html',
}
};
var req = http.request(options, function(res) {
console.log('Status: ' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (body) {
console.log('Body: ' + body);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(
'{"text": "test string"}'
);
req.end();
참고 사이트
- http://httpbin.org : 각종 HTTP 요청들에 대한 응답을 테스트할 수 있는 사이트
'1. 연구 모듈 > Node.js' 카테고리의 다른 글
| [Node.js] 폼 전송 및 쿠키 저장 (request 모듈 사용) (0) | 2016.10.18 |
|---|---|
| [Node.js] HTML 파싱하기 (cheerio 모듈 사용) (0) | 2016.09.27 |
| [Node.js] HTTP 요청하기 (request 모듈 사용) (0) | 2016.09.26 |
| [겉핥기 프로젝트] Node.js 개발 환경 (0) | 2016.08.31 |


