HTTP server
- HTTP server를 생성하기 위해 http모듈을 로드
- http.createServer([requestListener])는 http.Server의 새로운 인스턴스를 반환
- 반한된 인스턴스의 메소드 listen을 호출하여 접속 대기를 시작
요청이 발생 했을 때, 서버가 특정 동작을 수행하게 하려면 콜백함수를 지정해야 함. requestListener는 request event가 발생했을 때 자동 호출될 콜백 함수!
// server.js
// Node.js에 기본 내장되어 있는 http 모듈을 로드한다
var http = require("http");
// http 모듈의 createServer 메소드를 호출하여 HTTP 서버 생성
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"}); // (1)
response.write("Hello World"); // (2)
response.end(); // (3)
}).listen(8082);
실행
$ node server.js
- (1) 요청(request)이 올 때마다 response.writeHead() 함수를 사용해서 HTTP status 200과 content-type을 응답 헤더로 보내고,
- (2) response.write()로 HTTP 응답 바디에 "Hello World" 텍스트를 담아 보낸다.
- (3) 마지막으로 response.end()로 응답을 마무리한다.
url&query string
요청 URL과 GET/POST 파라미터를 router로 전달하면 router는 어떤 코드를 실행할지 결정할 수 있어야 한다. 즉, 전달된 요청 URL과 파라미터에 따라 서버의 할 일이 정해지는데 서버의 할 일을 수행하는 함수를 request handler라고 한다.
url과 querystring 모듈을 이용해 request 객체에 접근할 수 있다. url 모듈은 URL의 각각의 부분(URL path와 query string)을 추출할 수 있는 메소드를 제공한다. querystring 모듈은 query string을 request 파라미터로 파싱 하는데 사용한다. 또한, POST 요청의 body를 파싱하는 데도 사용된다.
var http = require("http");
var url = require("url");
http.createServer(function(request, response){
var pathname = url.parse(request.url).pathname;
console.log("Path name is " + pathname);
var query = url.parse(request.url, true).query;
console.log("Request parameter is ", query);
response.writeHead(200, {"Content-Type": "text/html"});
response.write(
"<h1>Path name is " + pathname + "</h1>" +
"<h1>Request parameter is " + JSON.stringify(query) + "</h1>");
response.end();
}).listen(8082);
console.log("Server has started.");
결과
localhost:8082/user?name=lee
Path name is /user
Request parameter is {"name":"lee"}
예제)
http 메소드 추출하기
req.method
http.createServer((req, res) => {
if(req.method == ' GET'){
console.log('GET request');
}else if(req.method == ' POST'){
console.log('POST request');
}
}
querystring 추출하기
URL.parse()
var URL = require('url');
http.createServer((req, res) => {
const q = URL.parse(req.headers['referer']).query;
console.log("q : ", q);
}
https://localhost:8082/info?a=b 일 경우,
결과
q : a=b
url 추출하기
req.headers
http.createServer((req, res) => {
console.log("req.headers['referer'] : ", typeof req.headers['referer'], req.headers['referer']);
}
결과
req.headers['referer'] : string http://localhost:8082/info?a=b
=> type은 string
header 정보에서 파일 추출해보기
http.createServer((req, res) => {
console.log(req.url);
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'server-name' : '15951'});
res.write(`<h2>distribute</h2>`);
var body = "";
req.on('data',function(data){
body = body + data;
body = JSON.parse(body);
console.log(body.file_name);
});
req.on('end', function () {
res.end(`<p>${body.file_name}</p>`);
});
}
결과
=>vscode에 'Thunder Client' 다운받아서 실행 결과 확인해볼 수 있다.
Location 지정하기
상태코드가 3xx일때만 브라우저가 이동한다.
res.statusCode = 301; // 상태코드
res.setHeader('Location','http://www.naver.com/');
cookie 지정하기
방법 1)
res.setHeader('Set-Cookie','abd=a;');
방법 2)
res.writeHead(200, {
'Set-Cookie':[
'first-cookie=1',
`Permanent=cookies; Max-Age=${60*60}` // 60초 * 60분 * 24시간 * 30일
]
});
방법 3)
let date = new Date(Date.now() + 3600);
date = date.toUTCString();
res.setHeader('Set-Cookie',"user=John; expires=" + date);
[참고]
https://www.w3schools.com/nodejs/nodejs_http.asp#
Node.js HTTP Module
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
https://velog.io/@hanblueblue/Node.js-2.-%EC%84%9C%EB%B2%84-%EC%97%B0%EC%8A%B5
[Node.js] 2. 서버 연습
서버 예제 코드를 따라해본다.
velog.io
https://poiemaweb.com/nodejs-file-upload-example
Node.js file upload example | PoiemaWeb
Node.js file upload example
poiemaweb.com
[웹 프로그래밍] HTTP 상태 코드 표(100 ~ 500) 전체 요약 정리
서버에서의 처리 결과는 응답 메시지의 상태 라인에 있는 상태 코드(status code)를 보고 파악할 수 있습니다. 상태 코드는 세 자리 숫자로 되어 있는데 첫 번째 숫자는 HTTP 응답의 종류를 구분하는
hongong.hanbit.co.kr
'인턴(2023.07. ~ 2023.12.) > 스크립트 송출 서버 개발' 카테고리의 다른 글
JS - Promise (0) | 2023.08.28 |
---|---|
인메모리 컴퓨팅 (0) | 2023.08.10 |
Node.js - Cluster (0) | 2023.08.09 |
HTTP와 HTTPS (0) | 2023.08.09 |
웹 서비스 구조 (0) | 2023.08.08 |