http
The http module provides Node.js-compatible HTTP client and server APIs for JSH applications.
request()
Creates a ClientRequest object.
Supported signatures:
request(url[, options][, callback])request(options[, callback])Returns:
ClientRequestIf
callbackis provided, it receivesIncomingMessagewhen a response arrives.
Syntax
request(url[, options][, callback])
request(options[, callback])Main request options
url(stringorURL)protocol,host,hostname,port,pathmethodheadersauth(converted toAuthorization: Basic ...)agent
Usage example
| |
get()
Shortcut for GET requests. Internally creates a request and calls end() automatically.
Supported signatures:
get(url[, options][, callback])get(options[, callback])Returns:
ClientRequestIf
callbackis omitted, handle the response with theresponseevent listener.
Syntax
get(url[, options][, callback])
get(options[, callback])status
HTTP status-code map.
Examples:
http.status.OKhttp.status.NotFoundhttp.status.InternalServerError
Behavior notes
response.okistruefor status codes in the200-299range.- Keys in
response.headersare normalized to lowercase. setHeader()/getHeader()/hasHeader()/removeHeader()treat header names case-insensitively.- Multiple
write()calls accumulate request body data before sending.
ClientRequest
Outgoing request object returned by request() / get().
ClientRequest header methods
setHeader(name, value)getHeader(name)hasHeader(name)removeHeader(name)getHeaders()getHeaderNames()
Usage example
| |
ClientRequest.write()
Writes body chunks.
chunksupportsstringandUint8Array- returns
trueon success,falseon failure
Syntax
write(chunk[, encoding][, callback])ClientRequest.end()
Finishes and sends the request.
- If
callbackis provided, it receives the response object (IncomingMessage).
Syntax
end([data[, encoding]][, callback])ClientRequest.destroy()
Destroys request object and optionally emits an error.
Syntax
destroy([err])ClientRequest events
response(IncomingMessage)error(Error)end()
IncomingMessage
HTTP response object.
Main properties
statusCodestatusMessageok(true for 2xx)headersrawHeadershttpVersioncompleteraw(internal Go response object)
IncomingMessage body methods
text([encoding])json()readBody([encoding])readBodyBuffer()text()andreadBody()useutf-8by default.json()can throw if parsing fails.
IncomingMessage utility methods
setTimeout(msecs[, callback])close()
Response bodies are typically closed automatically in normal processing flow, and close() can be called explicitly when needed.
Usage example
| |
Server
HTTP server object.
Creation
new Server([options])Options
network:tcporunix(default:tcp)address:host:portor unix socket path
Server route and static methods
get(path, handler)static(path, root)staticFile(path, file)
Server template methods
loadHTMLFiles(...files)loadHTMLGlob(pattern)
Server lifecycle methods
serve([callback])close([callback])
serve(callback) receives { network, address }.
Usage example
| |
Server context
Handler receives ctx with request and response helpers.
Request helpers
ctx.request.pathctx.request.queryctx.request.bodyctx.request.getHeader(name)ctx.param(name)ctx.query(name)
Response helpers
ctx.setHeader(name, value)ctx.redirect(status, url)ctx.abort()ctx.text(status, format[, ...args])ctx.json(status, data[, { indent: boolean }])ctx.html(status, template, data)ctx.yaml(status, data)ctx.toml(status, data)ctx.xml(status, data)
Client examples
GET request (callback)
| |
GET request (event listener)
| |
Set and read request headers
| |
Read response headers and body
| |
POST request with JSON
| |
Handle 404 responses
| |
Request with URL object
When the server is running, send a GET request and parse the JSON body.
| |
Server examples
Simple HTTP server
Runs a server on 127.0.0.1:56802 and returns JSON from /hello/:name.
| |
curl -o - http://127.0.0.1:56802/hello/Karl{"message":"greetings","name":"Karl"}Static content and redirect
| |
RESTful API
| |
- GET
curl -o - http://127.0.0.1:56802/movies[
{ "id": 59793, "studio": [ "Paramount" ], "title": "Indiana Jones" },
{ "id": 64821, "studio": [ "Lucasfilm" ], "title": "Star Wars" }
]- POST
curl -o - -X POST http://127.0.0.1:56802/movies \
-H "Content-Type: application/json" \
-d '{"title":"new movie", "id":12345, "studio":["HomeVideo"]}'- DELETE
curl -v -o - -X DELETE http://127.0.0.1:56802/movies/12345< HTTP/1.1 204 No Content
< Content-Type: text/plain; charset=utf-8
< Date: Thu, 08 May 2025 20:39:34 GMT
<HTML templates
This line enables the server to load all HTML template files matching the /*.html pattern.
These templates allow the server to dynamically generate HTML responses by combining predefined layouts with data provided during runtime.
| |
- HTML Template Code
movie_list.html
<html>
<body>
<h1>{{.subject}}</h1>
<ol>
{{range .list }}
<li> {{.id}} {{.title}} {{.studio}}
{{end}}
</ol>
</body>
</html>Sends a GET request to the /movielist endpoint.
The server responds with an HTML page generated using the movie_list.html template and the obj data.
curl -o - http://127.0.0.1:56802/movielist<html>
<body>
<h1>Movie List</h1>
<ol>
<li> 59793 Indiana Jones [Paramount]
<li> 64821 Star Wars [Lucasfilm]
</ol>
</body>
</html>