Client and Server Example
exports.endpoint = async function (request, response)
{
if (request.method === "GET")
return renderPage(response);
if (request.method == 'POST')
return response.end(JSON.stringify((await getRequestBody(request)).toUpperCase()));
}
async function getRequestBody(request)
{
var body = "";
return new Promise(function (resolve)
{
request.on("data", data => body += data);
request.on('end', () => resolve(JSON.parse(body)));
});
}
function renderPage(response)
{
response.setHeader("Content-Type", "text/html");
response.end(`
<!DOCTYPE HTML>
<html>
<body>
<script type = "application/javascript">
async function serverCapitalize()
{
const input = document.getElementById("input");
const response = await fetch(window.location, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(input.value)
});
input.value = await response.json();
}
</script>
<input id = "input" type = "text" value = "hi">
<button type = "button" onClick = "serverCapitalize()">Click me to capitalize on the server</button>
</body>
</html>`);
}
no comments