Created
July 15, 2021 23:22
-
-
Save ProfAvery/efd46e1703cb2b0db1b705b096ffa0b6 to your computer and use it in GitHub Desktop.
How forms are handled on the server-side
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
#!/usr/bin/env node | |
const http = require('http') | |
const url = require('url') | |
const qs = require('querystring') | |
function formHandler (request, response) { | |
response.write(`method: ${request.method}\n`) | |
response.write(`url: ${request.url}\n`) | |
if (request.method === 'GET') { | |
const relativeUrl = new url.URL(request.url, 'relative:///') | |
const obj = Object.fromEntries(relativeUrl.searchParams) | |
const params = JSON.stringify(obj, null, 2) | |
response.end(`parameters: ${params}\n\n`) | |
} else if (request.method === 'POST') { | |
let body = '' | |
request.on('data', chunk => { | |
body += chunk | |
}) | |
request.on('end', () => { | |
response.write(`body: ${body}\n`) | |
const parsedQueryString = qs.parse(body) | |
const params = JSON.stringify(parsedQueryString, null, 2) | |
response.end(`parameters: ${params}\n\n`) | |
}) | |
} | |
} | |
const server = http.createServer(formHandler) | |
server.listen(8000) | |
console.log('Waiting for request...') |
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
<body> | |
<form method="POST" action="http://localhost:8000/form"> | |
<p> | |
<label for="name">Name:</label> | |
<input type="text" id="name" name="name" /> | |
</p> | |
<p> | |
<label for="email">Email:</label> | |
<input type="email" id="email" name="address" /> | |
</p> | |
<p> | |
<label for="subject">Subject:</label> | |
<input type="text" id="subject" name="heading" /> | |
</p> | |
<p> | |
<textarea name="message" cols="80" rows="24" placeholder="Message"></textarea> | |
</p> | |
<p> | |
<input type="submit" /> | |
</p> | |
</form> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment