How to Submit Form with Node.js
Form inside JS file
You correctly created and served a basic HTML form directly via resp.write()
:
const http = require("http");
http
.createServer((req, resp) => {
resp.writeHead(200, {
"Content-Type": "text/html",
});
resp.write(`
<form action="/submit" method="POST">
<input type="text" placeholder="Enter username" name="name" />
<input type="text" placeholder="Enter email" name="email" />
<button>Submit</button>
</form>
`);
resp.end();
})
.listen(3200);
This works fine, though you're not handling the actual POST data yet — just confirming routing works.
Conditional Handling of /submit
if (req.url === "/") {
// form page
} else if (req.url === "/submit") {
// confirmation message
}
This conditional routing is correct for handling basic URL-based navigation.
Using a separate form.html
file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Form page</title>
</head>
<body>
<form action="/submit" method="POST">
<input type="text" placeholder="Enter username" name="name" />
<input type="text" placeholder="Enter email" name="email" />
<button>Submit</button>
</form>
</body>
</html
Perfectly structured form with POST
method and inputs.
Load HTML File via fs
const http = require('http');
const fs = require('fs');
http.createServer((req, resp) => {
fs.readFile('html/form.html', 'utf-8', (error, data) => {
if (error) {
resp.writeHead(500, { "content-type": 'text/plain' });
resp.end('internal server error');
return;
}
resp.writeHead(200, { "content-type": 'text/html' });
if (req.url == '/') {
resp.write(data);
} else if (req.url == '/submit') {
resp.write('<h1>Data submitted</h1>');
}
resp.end();
});
}).listen(3200);
Everything is correct:
- Loads HTML file when
GET /
- Shows confirmation message when
/submit
is requested - Responds with correct headers
- Properly handles
fs.readFile
errors