Custom body

I checked out the example for writing a simple HTTP server to only serve text at this link. How would I write a handler function that accepts a string parameter for the body content? Am I being stupid here?
8 Replies
marvinh.
marvinh.β€’7mo ago
The handler function is typically the function that is passed into Deno.serve and only ever receives the Request object and a second connection info parameter. The handler function is called by Deno.serve under the hood and cannot be changed. If you want to read the request body as text, you can do so by doing:
Deno.serve(async req => {
const text = await req.text()
console.log(text)
return new Response("ok")
});
Deno.serve(async req => {
const text = await req.text()
console.log(text)
return new Response("ok")
});
See https://developer.mozilla.org/en-US/docs/Web/API/Request
πŸŽ€π”Έβ„•π”Ύπ”Όπ•ƒ π”»π•†π•ƒπ•ƒπ”½π”Έβ„‚π”ΌπŸŽ€πŸ‡΅πŸ‡Έ
But I would like to serve a text response and supply that text. How would that work? Not in the request. In the server.
marvinh.
marvinh.β€’7mo ago
Would work the same way:
const SERVER_TEXT = "foobar"

Deno.serve(async req => {
return new Response(`ok ${SERVER_TEXT}`)
});
const SERVER_TEXT = "foobar"

Deno.serve(async req => {
return new Response(`ok ${SERVER_TEXT}`)
});
πŸŽ€π”Έβ„•π”Ύπ”Όπ•ƒ π”»π•†π•ƒπ•ƒπ”½π”Έβ„‚π”ΌπŸŽ€πŸ‡΅πŸ‡Έ
I would like to dynamically build the HTML string and then pass that to the serve function Deno has. Global variables are not an option.
marvinh.
marvinh.β€’7mo ago
What's stopping you from doing that? You can call any functions from within the serve callback and build whatever your heart desires on the fly
Deno.serve(async () => {
const html = dynamicallyBuildHTML();
return new Response(html, {
headers: {Β "Content-Type": "text/html; charset=utf-8" }
})
});
Deno.serve(async () => {
const html = dynamicallyBuildHTML();
return new Response(html, {
headers: {Β "Content-Type": "text/html; charset=utf-8" }
})
});
πŸŽ€π”Έβ„•π”Ύπ”Όπ•ƒ π”»π•†π•ƒπ•ƒπ”½π”Έβ„‚π”ΌπŸŽ€πŸ‡΅πŸ‡Έ
So I cannot supply the html as a parameter? Because I want to supply html to the handler. That cannot be done? Sorry for the late response, busy day.πŸ™ˆ
crowlKats
crowlKatsβ€’7mo ago
Because I want to supply html to the handler
not sure I understand; what would that do?
πŸŽ€π”Έβ„•π”Ύπ”Όπ•ƒ π”»π•†π•ƒπ•ƒπ”½π”Έβ„‚π”ΌπŸŽ€πŸ‡΅πŸ‡Έ
I wanna have two functions: One that builds an html string and a function that serves that html and that last function takes the html as an argument. If a certain event happens, the html changes and the function that generates the html is invoked again and that html is passed to the serving function again..