Skip to main content
On this page

Using fetch

To exchange data between the server and the client, you can use the standard fetch API.

Tip

For convenient management and synchronization of schemas, you can:

  • Extract them into separate files (especially if you use a monorepo or full-stack frameworks like Next.js, Astro, etc.).
  • Package your schemas into a separate private or public npm module to reuse across multiple projects.

Example

For convenience, we will create and extract the data schema into a separate file.

data.js
import { Serializer, t } from "encodexx";
export const serializer = new Serializer([
{
xValue: t.float64,
yValue: t.float64,
zValue: t.optional(t.float64),
},
]);

Next, we create a server using Express to handle the request.

server.js
import express from "express";
import { serializer } from "./data";
const app = express();
app.use(express.raw({ type: "application/octet-stream" }));
app.post("/", (req, res) => {
const data = serializer.decode(req.body);
console.log("Received data", data.slice(0, 5));
const response = new Array(100);
response.fill({ xValue: Math.random(), yValue: Math.random(), zValue: Math.random() });
// Encode the data and send it back
const encoded = Buffer.from(serializer.encode(response).uint8Array);
console.log("Sending data", response.slice(0, 5));
res.set("Content-Type", "application/octet-stream");
res.send(encoded);
});
app.listen(3000, () => {
console.log("Server started on http://localhost:3000");
});

Then on the client side, we can send data to the server and receive a response.

client.js
import { serializer } from "./data";
const data = new Array(5);
data.fill({ xValue: 2.3463, yValue: 43.321223 });
const body = serializer.encode(data).buffer;
fetch("http://localhost:3000", {
method: "POST",
body,
headers: {
// Indicate that we are sending binary data
"Content-Type": "application/octet-stream",
},
})
.then((response) => response.arrayBuffer())
.then((buffer) => serializer.decode(buffer))
.then((data) => console.log("Received data, length", data.length, data.slice(0, 5)));