@jsh/http

Since v8.0.52

request()

Convenient function for making HTTP client requests.

Syntax
request(url, option)
Parameters
  • url String destination address. e.g. http://192.168.0.120/api/members
  • option Object optional ClientRequestOption.
Return value

Object ClientRequest

Usage example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const {println} = require("@jsh/process");
const http = require("@jsh/http")
try {
    req = http.request("http://127.0.0.1:29876/hello")
    req.do((rsp) => {
        println("url:", rsp.url);
        println("error:", rsp.error());
        println("status:", rsp.status);
        println("statusText:", rsp.statusText);
        println("body:", rsp.text());
    })
} catch (e) {
    println(e.toString());
}

Client

The HTTP client.

Creation
ConstructorDescription
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
Return value

Object

PropertyTypeDescription
statusNumberhttp status code
statusTextStringhttp status message
urlStringrequest url
errorStringerror message
Usage example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const http = require("@jsh/http");

const client = new http.Client()
client.do(
    "http://127.0.0.1:29876/hello",
    { method:"GET" }, 
    (rsp)=>{
        println("url:", rsp.url);
        println("error:", rsp.error());
        println("status:", rsp.status);
        println("statusText:", rsp.statusText);
        println("content-type:", rsp.headers["Content-Type"]);
        println("body:", rsp.text());
    })

ClientRequestOption

OptionTypeDefaultDescription
methodStringGETGET, POST, DELETE, PUT…
headersObject
bodyStringContent to send
unixStringUnix 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

PropertyTypeDescription
statusNumberstatus code. e.g. 200, 404
statusTextStringe.g. 200 OK
headersObjectresponse headers
methodStringrequest method
urlStringrequest url
errorStringerror message

Server

The HTTP server listener.

Usage example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const http = require("@jsh/http")
const lsnr = new http.Listener({
    network:'tcp',
    address:'127.0.0.1:8080',
})
lsnr.get("/hello/:name", (ctx) => {
    let name = ctx.param("name");
    let hello = ctx.query("greeting");
    hello = hello == "" ?  "hello" : hello;
    ctx.JSON(http.status.OK, {
        greeting: hello,
        name:  name,
    })
})
lsnr.static("/html", "/html")
lsnr.listen();
Creation
ConstructorDescription
new Listener(options)Instantiates a HTTP client
Options
OptionTypeDefaultDescription
networkStringtcptcp, unix
addressStringhost: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 listener 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:

  1. Universal Method Handling: Handles all HTTP methods for a specific route.
  2. 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_path String The 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
1
2
3
4
5
6
7
const http = require("@jsh/http");

const lsnr = new http.Listener({ network: 'tcp', address: '127.0.0.1:8080' });
lsnr.all("/api/resource", (ctx) => {
    ctx.JSON(http.status.OK, { message: "Handled all methods" });
});
lsnr.listen();

get()

The get() function is a method of the HTTP server listener 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_path String The 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
1
2
3
4
5
6
7
8
const http = require("@jsh/http");

const lsnr = new http.Listener({ network: 'tcp', address: '127.0.0.1:8080' });
lsnr.get("/hello/:name", (ctx) => {
    const name = ctx.param("name");
    ctx.JSON(http.status.OK, { message: `Hello, ${name}!` });
});
lsnr.listen();

post()

The post() function is a method of the HTTP server listener 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_path String The 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
1
2
3
4
5
6
7
8
const http = require("@jsh/http");

const lsnr = new http.Listener({ network: 'tcp', address: '127.0.0.1:8080' });
lsnr.post("/submit", (ctx) => {
    const data = ctx.body; // Access the request body
    ctx.JSON(http.status.Created, { message: "Data received", data: data });
});
lsnr.listen();

put()

Add a route to handle PUT method.

Syntax
put(request_path, handler)
Parameters
  • request_path String
  • handler (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_path String
  • handler (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 listener 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:

  1. Static File Serving: Serves files from a specified directory for requests matching a given path.
  2. Efficient Resource Delivery: Ideal for delivering static assets in web applications.
Syntax
static(request_path, dir_path)
Parameters
  • request_path String The URL path to match.
  • dir_path String The directory path containing the static files to serve.
Return value

None.

Usage example
1
2
3
4
5
const http = require("@jsh/http");

const lsnr = new http.Listener({ network: 'tcp', address: '127.0.0.1:8080' });
lsnr.static("/public", "/path/to/static/files");
lsnr.listen();

staticFile()

The staticFile() function is a method of the HTTP server listener 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_path String The URL path to match.
  • file_path String The file path of the static file to serve.
Return value

None.

Usage example
1
2
3
4
5
const http = require("@jsh/http");

const lsnr = new http.Listener({ network: 'tcp', address: '127.0.0.1:8080' });
lsnr.staticFile("/favicon.ico", "/path/to/favicon.ico");
lsnr.listen();

listen()

The listen() function is a method of the HTTP server listener 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
listen()
listen(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
1
2
3
4
5
6
const http = require("@jsh/http");

const lsnr = new http.Listener({ network: 'tcp', address: '127.0.0.1:8080' });
lsnr.listen((result) => {
    console.log(`Server is listening on ${result.network}://${result.message}`);
});

close()

Stop and shutdown the server.

Syntax
close()
Parameters

None.

Return value

None.

ServerResult

Properties
PropertyTypeDescription
networkStringe.g. tcp
messageStringe.g. 127.0.0.1:8080

ServerContext

Properties
PropertyTypeDescription
requestObjectServerRequest

abort()

Syntax
abort()
Parameters

None.

Return value

None.

redirect()

Syntax
redirect(statusCode, url)
Parameters
  • statusCode Number HTTP status code. e.g. 302, http.status.Found
  • url String address to redirect.
Return value

None.

setHeader()

Syntax
setHeader(name, value)
Parameters
  • name String
  • value String
Return value

None.

param()

Syntax
param(name)
Parameters
  • name String
Return value
  • String

query()

Syntax
query(name)
Parameters
  • name String
Return value
  • String

TEXT()

Syntax
TEXT(statusCode, content)
Parameters

None.

Return value

None.

JSON()

Syntax
JSON(statusCode, content)
Parameters

None.

Return value

None.

HTML()

Syntax
HTML(statusCode, content)
Parameters

None.

Return value

None.

XML()

Syntax
XML(statusCode, content)
Parameters

None.

Return value

None.

YAML()

Syntax
YAML(statusCode, content)
Parameters

None.

Return value

None.

TOML

Syntax
TOML(statusCode, content)
Parameters

None.

Return value

None.

ServerRequest

Properties
PropertyTypeDescription
methodString
hostString
pathString
queryString
headerObject
bodyObject
remoteAddressString

getHeader()

Syntax
getHeader(name)
Parameters
  • name String head name. e.g. Content-Type, Content-Length
Return value

String header 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;
Last updated on