@jsh/http
Since v8.0.52request()
Convenient function for making HTTP client requests.
Syntax
request(url, option)Parameters
urlStringdestination address. e.g.http://192.168.0.120/api/membersoptionObjectoptional ClientRequestOption.
Return value
ObjectClientRequest
Usage example
| |
Client
The HTTP client.
Creation
| Constructor | Description |
|---|---|
| new Client() | Instantiates a HTTP client |
do()
The do() function is a method of the HTTP client that sends an HTTP request to a specified URL and processes the response. It supports optional request options (e.g., method, headers, body) and a callback function to handle the response.
Syntax
client.do(url)
client.do(url, option)
client.do(url, option, callback)Parameters
urlStringoptionObjectClientRequestOptioncallback(response) => {}callback function with ClientResponse.
Return value
Object
| Property | Type | Description |
|---|---|---|
| status | Number | http status code |
| statusText | String | http status message |
| url | String | request url |
| error | String | error message |
Usage example
| |
ClientRequestOption
| Option | Type | Default | Description |
|---|---|---|---|
| method | String | GET | GET, POST, DELETE, PUT… |
| headers | Object | ||
| body | String | Content to send | |
| unix | String | Unix Domain Socket file path |
If the unix option is specified, the HTTP client will attempt to connect to the server using the provided Unix domain socket file path.
ClientRequest
do()
The do() function is a method of the HTTP client that sends an HTTP request to a specified URL and processes the response.
Syntax
do(callback)Parameters
callback(response) => {}callback function.
Return value
None.
ClientResponse
Properties
| Property | Type | Description |
|---|---|---|
| status | Number | status code. e.g. 200, 404 |
| statusText | String | e.g. 200 OK |
| headers | Object | response headers |
| method | String | request method |
| url | String | request url |
| error | String | error message |
text()
Returns the entire response body as a single string.
json()
Parses the response body and returns it as a JSON object.
csv()
Parses the response body and returns it as an array of string arrays, where each inner array represents a row of CSV data.
Server
The HTTP server.
Usage example
| |
Creation
| Constructor | Description |
|---|---|
| new Server(options) | Instantiates a HTTP server |
Options
| Option | Type | Default | Description |
|---|---|---|---|
| network | String | tcp | tcp, unix |
| address | String | host:port, /path/to/file |
- TCP/IP:
{network:"tcp", address:"192.168.0.100:8080"} - Unix Domain Socket:
{network:"unix", address:"/tmp/http.sock"}
all()
The all() function is a method of the HTTP server that adds a route to handle all HTTP methods, including GET, POST, PUT, DELETE, and others. It allows you to define a single handler for multiple request types.
Key Features:
- Universal Method Handling: Handles all HTTP methods for a specific route.
- Custom Request Processing: Provides a callback function to process incoming requests using the context parameter, which contains request-specific details.
Syntax
all(request_path, handler)Parameters
request_pathStringThe URL path to match.handler(context) => {}A callback function that processes incoming requests, with the context parameter providing details like request headers, parameters, and body.
Return value
None.
Usage example
| |
get()
The get() function is a method of the HTTP server that adds a route to handle HTTP GET requests. It allows you to define a handler for processing incoming GET requests to a specific URL path.
Syntax
get(request_path, handler)Parameters
request_pathStringThe URL path to match.handler(context) => {}A callback function that processes incoming requests, with the context parameter providing details like request headers, parameters, and body.
Return value
None.
Usage example
| |
post()
The post() function is a method of the HTTP server that adds a route to handle HTTP POST requests. It allows you to define a handler for processing incoming POST requests to a specific URL path.
Syntax
put(request_path, handler)Parameters
request_pathStringThe URL path to match.handler(context) => {}A callback function that processes incoming requests, with the context parameter providing request-specific details.
Return value
None.
Usage example
| |
put()
Add a route to handle PUT method.
Syntax
put(request_path, handler)Parameters
request_pathStringhandler(context) => {}A callback function that processes incoming requests, with the context parameter providing request-specific details.
Return value
None.
delete()
Add a route to handle DELETE method.
Syntax
delete(request_path, handler)Parameters
request_pathStringhandler(context) => {}A callback function that processes incoming requests, with the context parameter providing request-specific details.
Return value
None.
static()
The static() function is a method of the HTTP server that defines a route to serve files from a specified static directory. It is useful for serving static assets like HTML, CSS, JavaScript, images, or other files in response to HTTP requests.
Key Features:
- Static File Serving: Serves files from a specified directory for requests matching a given path.
- Efficient Resource Delivery: Ideal for delivering static assets in web applications.
Syntax
static(request_path, dir_path)Parameters
request_pathStringThe URL path to match.dir_pathStringThe directory path containing the static files to serve.
Return value
None.
Usage example
| |
staticFile()
The staticFile() function is a method of the HTTP server that defines a route to serve a specific static file for a given request path. It is useful for serving individual files, such as a single HTML page, image, or configuration file, in response to HTTP requests.
Key Features:
- Single File Serving: Serves a specific file for a specified request path.
- Efficient Resource Delivery: Ideal for delivering individual static resources.
Syntax
staticFile(request_path, file_path)Parameters
request_pathStringThe URL path to match.file_pathStringThe file path of the static file to serve.
Return value
None.
Usage example
| |
loadHTMLGlob()
Syntax
loadHTMLGlob(pattern)Parameters
patternStringThe file path glob pattern.
Return value
None.
Usage example
| |
serve()
The serve() function is a method of the HTTP server that starts the server and blocks the control flow until the stop() function is called. It begins listening for incoming requests on the specified network and address.
Syntax
serve()
serve(callback)Parameters
callback(result)=>{}An optional callback function that receives a ServerResult object containing details like the network type and address.
Return value
None.
Usage example
| |
close()
Stop and shutdown the server.
Syntax
close()Parameters
None.
Return value
None.
ServerResult
Properties
| Property | Type | Description |
|---|---|---|
| network | String | e.g. tcp |
| message | String | e.g. 127.0.0.1:8080 |
ServerContext
Properties
| Property | Type | Description |
|---|---|---|
| request | Object | ServerRequest |
abort()
Syntax
abort()Parameters
None.
Return value
None.
redirect()
Syntax
redirect(statusCode, url)Parameters
statusCodeNumberHTTP status code. e.g.302,http.status.FoundurlStringaddress to redirect.
Return value
None.
setHeader()
Syntax
setHeader(name, value)Parameters
nameStringvalueString
Return value
None.
param()
Syntax
param(name)Parameters
nameString
Return value
String
query()
Syntax
query(name)Parameters
nameString
Return value
String
TEXT()
Syntax
TEXT(statusCode, content)Parameters
None.
Return value
None.
Usage example
| |
| |
JSON()
Syntax
JSON(statusCode, content)Parameters
None.
Return value
None.
Usage example
| |
| |
YAML()
Syntax
YAML(statusCode, content)Parameters
None.
Return value
None.
Usage example
| |
TOML
Syntax
TOML(statusCode, content)Parameters
None.
Return value
None.
Usage example
| |
XML()
Syntax
XML(statusCode, content)Parameters
None.
Return value
None.
Usage example
| |
HTML()
Syntax
HTML(statusCode, template, obj)Parameters
statusCodeNumberHTTP Response Status CodetemplateStringTemplate nameobjanyTemplate value
Return value
None.
Usage example
| |
- /templates/hello.html
<html>
<body>
<h1>Hello, {{.str}}!</h1>
<p>num: {{.num}}</p>
<p>bool: {{.bool}}</p>
</body>
</html>ServerRequest
Properties
| Property | Type | Description |
|---|---|---|
| method | String | |
| host | String | |
| path | String | |
| query | String | |
| header | Object | |
| body | Object | |
| remoteAddress | String |
getHeader()
Syntax
getHeader(name)Parameters
nameStringhead name. e.g.Content-Type,Content-Length
Return value
Stringheader value.
status
Defines http status codes.
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;