@jsh/http
Since v8.0.52request()
간단한 HTTP 클라이언트 요청 헬퍼 함수입니다.
사용 형식
request(url, option)매개변수
urlString요청 대상 주소입니다. 예:http://192.168.0.120/api/membersoptionObject선택적 ClientRequestOption입니다.
반환값
ObjectClientRequest
사용 예시
| |
Client
HTTP 클라이언트 객체입니다.
생성
| Constructor | 설명 |
|---|---|
| new Client() | HTTP 클라이언트를 생성합니다. |
do()
지정한 URL로 HTTP 요청을 전송하고 응답을 처리합니다. 메서드, 헤더, 본문 등 옵션과 콜백 함수를 함께 전달할 수 있습니다.
사용 형식
client.do(url)
client.do(url, option)
client.do(url, option, callback)매개변수
urlStringoptionObjectClientRequestOptioncallback(response) => {}ClientResponse를 인자로 받는 콜백입니다.
반환값
Object
| Property | Type | 설명 |
|---|---|---|
| status | Number | HTTP 상태 코드 |
| statusText | String | HTTP 상태 메시지 |
| url | String | 요청 URL |
| error | String | 오류 메시지 |
사용 예시
| |
ClientRequestOption
| 옵션 | 타입 | 기본값 | 설명 |
|---|---|---|---|
| method | String | GET | GET, POST, DELETE, PUT 등 HTTP 메서드 |
| headers | Object | 요청 헤더 | |
| body | String | 전송할 본문 | |
| unix | String | 유닉스 도메인 소켓 파일 경로 |
unix 옵션을 지정하면 해당 소켓 파일로 서버에 연결을 시도합니다.
ClientRequest
do()
ClientRequest 객체에서 콜백을 실행해 응답을 처리합니다.
사용 형식
do(callback)매개변수
callback(response) => {}응답을 처리할 콜백입니다.
반환값
없음.
ClientResponse
프로퍼티
| Property | Type | 설명 |
|---|---|---|
| status | Number | 상태 코드 (예: 200, 404) |
| statusText | String | 상태 메시지 (예: 200 OK) |
| headers | Object | 응답 헤더 |
| method | String | 요청 메서드 |
| url | String | 요청 URL |
| error | String | 오류 메시지 |
text()
응답 본문을 문자열로 반환합니다.
json()
응답 본문을 JSON 객체로 반환합니다.
csv()
응답 본문을 CSV 행 배열로 반환합니다.
Server
HTTP 서버 객체입니다.
사용 예시
| |
생성
| Constructor | 설명 |
|---|---|
| new Server(options) | HTTP 서버를 생성합니다. |
옵션
| 옵션 | 타입 | 기본값 | 설명 |
|---|---|---|---|
| network | String | tcp | tcp, unix |
| address | String | host:port, /path/to/file |
- TCP/IP 예시:
{network:"tcp", address:"192.168.0.100:8080"} - Unix 도메인 소켓 예시:
{network:"unix", address:"/tmp/http.sock"}
all()
모든 HTTP 메서드를 한 번에 처리할 라우트를 등록합니다.
사용 형식
all(request_path, handler)매개변수
request_pathString매칭할 URL 경로입니다.handler(context) => {}context를 사용해 요청 정보를 처리하는 콜백입니다.
반환값
없음.
사용 예시
| |
get()
GET 요청을 처리할 라우트를 등록합니다.
사용 형식
get(request_path, handler)매개변수
request_pathString매칭할 URL 경로입니다.handler(context) => {}요청을 처리할 콜백입니다.
반환값
없음.
사용 예시
| |
post()
POST 요청을 처리할 라우트를 등록합니다.
사용 형식
post(request_path, handler)매개변수
request_pathString매칭할 URL 경로입니다.handler(context) => {}요청 본문 등을 처리할 콜백입니다.
반환값
없음.
사용 예시
| |
put()
PUT 요청을 처리할 라우트를 등록합니다.
사용 형식
put(request_path, handler)매개변수
request_pathStringhandler(context) => {}요청 정보를 처리할 콜백입니다.
반환값
없음.
delete()
DELETE 요청을 처리할 라우트를 등록합니다.
사용 형식
delete(request_path, handler)매개변수
request_pathStringhandler(context) => {}요청 정보를 처리할 콜백입니다.
반환값
없음.
static()
정적 디렉터리를 라우트에 매핑합니다. HTML, CSS, JavaScript, 이미지 등 정적 자산 제공에 적합합니다.
사용 형식
static(request_path, dir_path)매개변수
request_pathString요청 경로 접두사입니다.dir_pathString제공할 디렉터리 경로입니다.
반환값
없음.
사용 예시
| |
staticFile()
지정한 파일을 특정 경로로 제공하도록 라우트를 등록합니다.
사용 형식
staticFile(request_path, file_path)매개변수
request_pathString매칭할 URL 경로입니다.file_pathString제공할 파일 경로입니다.
반환값
없음.
사용 예시
| |
loadHTMLGlob()
HTML 템플릿 파일을 일괄 로드합니다.
사용 형식
loadHTMLGlob(pattern)매개변수
patternString글롭 패턴입니다.
반환값
없음.
사용 예시
| |
serve()
서버를 시작하고 stop()이 호출될 때까지 대기합니다.
사용 형식
serve()
serve(callback)매개변수
callback(result)=>{}ServerResult를 인자로 받는 선택적 콜백입니다.
반환값
없음.
사용 예시
| |
close()
서버를 중지하고 종료합니다.
사용 형식
close()매개변수
없음.
반환값
없음.
ServerResult
프로퍼티
| 프로퍼티 | 타입 | 설명 |
|---|---|---|
| network | String | 예: tcp |
| message | String | 예: 127.0.0.1:8080 |
ServerContext
프로퍼티
| 프로퍼티 | 타입 | 설명 |
|---|---|---|
| request | Object | ServerRequest |
abort()
요청 처리를 즉시 중단합니다.
사용 형식
abort()매개변수
없음.
반환값
없음.
redirect()
지정한 상태 코드로 다른 URL에 리다이렉트합니다.
사용 형식
redirect(statusCode, url)statusCodeNumberHTTP 상태 코드 (예:302,http.status.Found)urlString이동할 주소
반환값
없음.
setHeader()
응답 헤더를 설정합니다.
사용 형식
setHeader(name, value)매개변수
nameStringvalueString
반환값
없음.
param()
라우트 경로 파라미터 값을 반환합니다.
사용 형식
param(name)nameString파라미터 이름
반환값
String파라미터 값
query()
쿼리 문자열 값을 반환합니다.
사용 형식
query(name)nameString쿼리 키
반환값
String쿼리 값
TEXT()
텍스트 응답을 전송합니다.
사용 형식
TEXT(statusCode, content)매개변수
없음.
반환값
없음.
사용 예시
| |
| |
JSON()
JSON 응답을 전송합니다.
사용 형식
JSON(statusCode, content)매개변수
없음.
반환값
없음.
사용 예시
| |
| |
YAML()
YAML 응답을 전송합니다.
사용 형식
YAML(statusCode, content)매개변수
없음.
반환값
없음.
사용 예시
| |
TOML
TOML 응답을 전송합니다.
사용 형식
TOML(statusCode, content)매개변수
없음.
반환값
없음.
사용 예시
| |
XML()
XML 응답을 전송합니다.
사용 형식
XML(statusCode, content)매개변수
없음.
반환값
없음.
사용 예시
| |
HTML()
HTML 템플릿을 렌더링해 응답합니다.
사용 형식
HTML(statusCode, template, obj)statusCodeNumberHTTP 응답 코드templateString템플릿 이름objany템플릿에 바인딩할 값
반환값
없음.
사용 예시
| |
- /templates/hello.html
<html>
<body>
<h1>Hello, {{.str}}!</h1>
<p>num: {{.num}}</p>
<p>bool: {{.bool}}</p>
</body>
</html>ServerRequest
프로퍼티
| Property | Type | 설명 |
|---|---|---|
| method | String | 요청 메서드 |
| host | String | 요청 호스트 |
| path | String | 요청 경로 |
| query | String | 쿼리 문자열 |
| header | Object | 요청 헤더 |
| body | Object | 요청 본문 |
| remoteAddress | String | 원격 주소 |
getHeader()
사용 형식
getHeader(name)매개변수
nameStringhead name. e.g.Content-Type,Content-Length
반환값
String헤더 값.
status
HTTP 상태 코드를 제공합니다.
const http = require("@jsh/http");
http.status.OK = 200;
http.status.Created = 201;
http.status.Accepted = 202;
http.status.NonAuthoritativeInfo = 203;
http.status.NoContent = 204;
http.status.ResetContent = 205;
http.status.PartialContent = 206;
http.status.MultipleChoices = 300;
http.status.MovedPermanently = 301;
http.status.Found = 302;
http.status.SeeOther = 303;
http.status.NotModified = 304;
http.status.UseProxy = 305;
http.status.TemporaryRedirect = 307;
http.status.PermanentRedirect = 308;
http.status.BadRequest = 400;
http.status.Unauthorized = 401;
http.status.PaymentRequired = 402;
http.status.Forbidden = 403;
http.status.NotFound = 404;
http.status.MethodNotAllowed = 405;
http.status.NotAcceptable = 406;
http.status.ProxyAuthRequired = 407;
http.status.RequestTimeout = 408;
http.status.Conflict = 409;
http.status.Gone = 410;
http.status.LengthRequired = 411;
http.status.PreconditionFailed = 412;
http.status.RequestEntityTooLarge = 413;
http.status.RequestURITooLong = 414;
http.status.UnsupportedMediaType = 415;
http.status.RequestedRangeNotSatisfiable = 416;
http.status.ExpectationFailed = 417;
http.status.Teapot = 418;
http.status.UnprocessableEntity = 422;
http.status.Locked = 423;
http.status.FailedDependency = 424;
http.status.TooEarly = 425;
http.status.UpgradeRequired = 426;
http.status.PreconditionRequired = 428;
http.status.TooManyRequests = 429;
http.status.RequestHeaderFieldsTooLarge = 431;
http.status.UnavailableForLegalReasons = 451;
http.status.InternalServerError = 500;
http.status.NotImplemented = 501;
http.status.BadGateway = 502;
http.status.ServiceUnavailable = 503;
http.status.GatewayTimeout = 504;
http.status.HTTPVersionNotSupported = 505;
http.status.VariantAlsoNegotiates = 506;
http.status.InsufficientStorage = 507;
http.status.LoopDetected = 508;
http.status.NotExtended = 510;
http.status.NetworkAuthenticationRequired = 511;