Skip to content

Commit

Permalink
Merge pull request #1046 from technosophos/sample/ts-router-post
Browse files Browse the repository at this point in the history
Add TS example of handling POST data from a router.
  • Loading branch information
itowlson authored Nov 21, 2023
2 parents 39fb719 + 144cef2 commit fbfd08f
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions content/api/hub/sample_ts_router_post.md
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.

0 comments on commit fbfd08f

Please sign in to comment.