-
Notifications
You must be signed in to change notification settings - Fork 74
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1046 from technosophos/sample/ts-router-post
Add TS example of handling POST data from a router.
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
title = "Handle POST Requests with Spin's JS/TS Router" | ||
template = "render_hub_content_body" | ||
date = "2023-11-15T00:00:00Z" | ||
content-type = "text/html" | ||
tags = ["typescript", "javascript", "router"] | ||
|
||
[extra] | ||
author = "technosophos" | ||
type = "hub_document" | ||
category = "Sample" | ||
language = "JS/TS" | ||
created_at = "2023-11-15T00:00:00Z" | ||
last_updated = "2023-11-15T00:00:00Z" | ||
spin_version = ">v2.0" | ||
summary = "Handle POST data from within Spin's JS/TS Router" | ||
url = "https://github.com/technosophos/ts-router-post" | ||
keywords = "typescript, javascript, router" | ||
|
||
--- | ||
|
||
This shows one technique for handling POST data using the `Router` object [built into the JS/TS SDK](https://developer.fermyon.com/spin/v2/javascript-components) for Spin. | ||
|
||
This example illustrates how to pass the HTTP body from Spin's SDK all the way to your end function without needing to use middleware. | ||
|
||
```typescript | ||
export const handleRequest: HandleRequest = async function (request: HttpRequest): Promise<HttpResponse> { | ||
let router = Router() | ||
|
||
// This gets the base path from the request, which is considered better | ||
// than hardcoding it. Now, when the `route` is changed in spin.toml, | ||
// our code does not need to change. | ||
let basePath = request.headers["spin-component-route"] | ||
|
||
// Note that we pass `request.body` as the second param. | ||
// That contains an ArrayBuffer with the encoded body. | ||
router.post(basePath, (req, body) => { | ||
|
||
// Decode the ArrayBuffer into a string | ||
let decodedBody = decoder.decode(body) | ||
return { | ||
status: 200, | ||
headers: { "content-type": "text/plain" }, | ||
body: decodedBody | ||
} | ||
}) | ||
// IMPORTANT: We pass the request body as the second param. | ||
return await router.handleRequest(request, request.body) | ||
} | ||
``` | ||
|
||
Check out the GitHub repository for a full runnable example. |