GUIDES HTTP Server Respond to Request
About
Binary Data
Captive Portal
DNS
DNS Service Discovery
EventSource
Files
HTTP
HTTP Server
Implementing ECMA-419 Modules
Key-Value Storage
Logging
MQTT
Optimizing Embedded JavaScript
Streams
Time
Time Callbacks
Transport Layer Security (TLS)
WebSocket
WebSocket Server
Wi-Fi
Wi-Fi Access Point
Overview
Create Server
Route Request
Respond to Request
Respond to Request with File
Receive Request Body
Receive Request Body to File
About
Binary Data
Overview
Convert String to ArrayBuffer
Convert ArrayBuffer to String
Convert ArrayBuffers to String
Handle Errors Converting ArrayBuffer to String
Immutable ArrayBuffers
Resize an ArrayBuffer
Combine ArrayBuffers
Convert Base64 to Binary Data
Convert Binary Data to Base64
Convert Binary Data to Hex
Convert Hex to Binary Data
Calculate CRC for Binary Data
Compress Binary Data – One Buffer
Compress Binary Data – Streaming
Decompress Binary Data – One Buffer
Decompress Binary Data – Streaming
Captive Portal
Overview
Create Captive Portal
Close Captive Portal
Provide Web Pages for Captive Portal
Get Information from Captive Portal
DNS
Overview
Resolve Name
Resolve Multiple Names
DNS Service Discovery
Overview
Claim Local Name
Advertise Services
Discover Services
EventSource
Overview
Connect
Connect Securely
Close
Receive
Connection Information
Files
Overview
Create, Open, and Close File
Read File
Write File
Delete File
Get File Information
Create Directory
Enumerate Directory
Delete Directory
Open Directory
HTTP
Overview
Make Request using fetch()
Make Secure Request using fetch()
Send Request Headers using fetch()
Receive Response Headers using fetch()
Send Request Body using fetch()
Make Request using HTTP Client
Make Secure Request using HTTP Client
Send Request Headers using HTTP Client
Receive Response Headers using HTTP Client
Send Request Body using HTTP Client
HTTP Server
Overview
Create Server
Route Request
Respond to Request
Respond to Request with File
Receive Request Body
Receive Request Body to File
Implementing ECMA-419 Modules
Overview
Constructor Sets target
Constructor IO
Constructor Clean-up on Failure
close() and [Symbol.dispose]
Calling Callbacks
Setting Options with configure()
Keep Instance Surface Clean
Key-Value Storage
Overview
Read and Write Values using Web Storage
Delete Keys using Web Storage
Enumerate Keys using Web Storage
Read and Write Values using Key-Value Pair
Change Data Formats using Key-Value Pair
Delete Keys using Key-Value Pair
Enumerate Keys using Key-Value Pair
Logging
Overview
Logging with Console
Logging with trace()
MQTT
Overview
Connect to MQTT Server using MQTT()
Connect Securely to MQTT Server using MQTT()
Close Connection using MQTT()
Publish Message using MQTT()
Subscribe to Topic using MQTT()
Receive Messages using MQTT()
Get Connection Information using MQTT()
Connect to MQTT Server using MQTT Client
Connect Securely to MQTT Server using MQTT Client
Close Connection using MQTT Client
Publish Message using MQTT Client
Subscribe to Topic using MQTT Client
Receive Messages using MQTT Client
Optimizing Embedded JavaScript
Overview
When to Optimize
Know Where to Optimize
Loop through an Array
Iterate Over a String
Build a String
Avoid Copying Buffers
Accessing Properties
Map versus Object
Append to an Array
Operate on Bits
Define Class Methods
Streams
Overview
Time
Overview
Get Unix Time
Get Time of Day
Get Date
Get Time Since System Start
Get Microseconds
Set System Date and Time
How Time and Timezone are Initialized
Get Time and Date from Real-Time Clock
Set Real-Time Clock Time
Get Time and Date from Network
Sleep
Time Callbacks
Overview
One-Time Callback
Repeating Callback
Repeating Callback with Initial Delay
Immediate Callback
Reschedule Callback
Cancel Callback
Suspend Callback
Transport Layer Security (TLS)
Overview
Include Public Certificates
Include Private Certificates
Diagnostics
DER and PEM Certificates
WebSocket
Overview
Connect to Server using WebSocket()
Connect Securely to Server using WebSocket()
Close Connection using WebSocket()
Send Message using WebSocket()
Receive Message using WebSocket()
Get Connection Information using WebSocket()
Connect to Server using WebSocket Client
Connect Securely to Server using WebSocket Client
Close Connection using WebSocket Client
Send Message using WebSocket Client
Receive Message using WebSocket Client
Control Messages using WebSocket Client
Connect to Server using WebSocketStream
Connect Securely to Server using WebSocketStream
Close Connection using WebSocketStream
Send Message using WebSocketStream
Receive Message using WebSocketStream
WebSocket Server
Overview
Create WebSocket Server Endpoint
Accept WebSocket Request
Wi-Fi
Overview
Scan for Access Points
Scan Continuously for Access Points
Connect
Reconnect Automatically
Disconnect
Get Connection Information
Use Static IP Address
Wi-Fi Access Point
Overview
Create Access Point
Close Access Point
Get Information
Manage Stations
DNS Redirect
Provide HTTP Server

Respond to Request

If your complete response is available from onRoute(), you can use the static route module to reply. Your response can include HTTP headers and the HTTP status. If the status is omitted, it defaults to 200.

import StaticRoute
	from "embedded:network/http/server/route/static";

const server = new device.network.http.server.io({
	...device.network.http.server,
	onRoute(request) {
		if (("GET" === request.method) &&
			("/" === request.path)) {
			return {
				...StaticRoute,
				data: "<h1>Hello</h1>",
				status: 200,
				contentType: "text/html"
			}
		}
	}
});

A static route also accepts binary data as the response body.

This example uses the headers property to set the response headers.

import StaticRoute
	from "embedded:network/http/server/route/static";
import Headers from "headers";

const server = new device.network.http.server.io({
	...device.network.http.server,
	onRoute(request) {
		if (("GET" === request.method) &&
			("/rng" === request.path)) {
			const randomBytes = new Uint8Array(16);
			for (let i = 0; i < 16; i++)
				randomBytes[i] = Math.irandom(256);
			return {
				...StaticRoute,
				data: randomBytes,
				headers: new Headers([
					["content-type", "application/octet-stream"],
					["rng", "javascript"],
					["date", new Date().toUTCString()]
				])
			}
		}
	}
});

If your complete response is not available from onRoute(), such as when the response is dynamically generated, you can't use the static route. Instead, implement your own route handler.

This example route responds with a random number of letters from a to z. Notice that onResponse() reports the length of the complete response and onWritable() generates precisely the number of characters necessary to fill the output buffer.

Note that write() only accepts binary data such as an ArrayBuffer or Uint8Array. Text must be converted to binary to pass to write().

const server = new device.network.http.server.io({
	...device.network.http.server,
	onRoute(request) {
		if (("GET" === request.method) &&
			("/" === request.path))
			return dynamicRoute;
	}
});

const dynamicRoute = {
	onResponse(response) {
		const responseLength = 1024 + Math.irandom(8 * 1024);
		response.headers.set("content-length", responseLength);
		response.headers.set("content-type", "text/plain");
		this.respond(response);
	},
	onWritable(count) {
		const bytes = new Uint8Array(count);
		bytes[count - 1] = 10;
		for (let i = 0; i < count - 1; i++)
			bytes[i] = Math.irandom(97, 123); // a..z
		this.write(bytes);
	}
};

If you don't know the size of the response from onRoute(), you can implement a handler to send the response as an HTTP chunked response. This is similar to the preceding example, but you don't set the content-length header in onResponse(), you set the transfer-encoding header to "chunked", and you call write() with no arguments to signal the end of the response.

const server = new device.network.http.server.io({
	...device.network.http.server,
	onRoute(request) {
		if (("GET" === request.method) &&
			("/" === request.path))
			return dynamicRoute;
	}
});

const dynamicRoute = {
	onResponse(response) {
		this.remaining = 1024 + Math.irandom(8 * 1024);
		response.headers.set("content-type", "text/plain");
		response.headers.set("transfer-encoding", "chunked");
		this.respond(response);
	},
	onWritable(count) {
		if (0 === this.remaining)
			return void this.write();

		count = Math.min(this.remaining, count);
		this.remaining -= count;
		const bytes = new Uint8Array(count);
		bytes[count - 1] = 10;
		for (let i = 0; i < count - 1; i++)
			bytes[i] = Math.irandom(97, 123); // a..z
		this.write(bytes);
	}
};

You may not have the data for your response ready when onResponse() is called. In that case, you can call respond() later when the data is available. This example waits two seconds, and then calls fetch() to retrieve a web page to use for the response.

import Timer from "timer";
import { fetch } from "fetch";

const server = new device.network.http.server.io({
	...device.network.http.server,
	onRoute(request) {
		if (("GET" === request.method) &&
			("/" === request.path))
			return fetchRoute;
	}
});

const fetchRoute = {
	onResponse(response) {
		Timer.set(async () => {
			const fetchResponse = await fetch(
			"http://example.com");
			const data = await fetchResponse.arrayBuffer();
			response.headers.set(
				"content-type", "text/plain");
			response.headers.set(
				"content-length", data.byteLength);
			this.bytes = new Uint8Array(data);
			this.position = 0;
			this.respond(response);
		}, 2_000);
	},
	onWritable(count) {
		this.write(this.bytes.subarray(
			this.position, this.position + count));
		this.position += count;
	}
};