this is form example in html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS3 Contact Form</title>
</head>
<body>
<div id="contact">
<h1>Send an email</h1>
<form action="/myaction" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email address" />
<label for="message">Message:</label>
<textarea id="message" placeholder="What's on your mind?"></textarea>
<input type="submit" value="Send message" />
</fieldset>
</form>
</div>
</body>
</html>
and this is node.js function that run on the server:
var sys = require('sys'),
http = require('http');
http.createServer(function (req, res) {
switch (req.url)
case '/myaction':
res.end(?????);
break;
}
}).listen(8080);
sys.puts('Server running at http://127.0.0.1:8080/');
I have 2 questions:
- How can I call
myaction
function in the node.js from the html page? Because the html file runs on port 80 and node.js on 8080 (when I try to move the node.js to port 80 it writes "// Unhandled 'error' event") - In the node.js function where I put "?????" how can I get data from the html form. When I type req.html.body.name I don't get the data...
I'd like to expand on Obertklep's answer. In his example it is an NPM module called
body-parser
which is doing most of the work. Where he putsreq.body.name
, I believe he/she is usingbody-parser
to get the contents of the name attribute(s) received when the form is submitted.If you do not want to use Express, use
querystring
which is a built-in Node module. See the answers in the link below for an example of how to usequerystring
.It might help to look at this answer, which is very similar to your quest.
Using
http.createServer
is very low-level and really not useful for creating web applications as-is.A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using
npm install express
.When you have, you can create a basic application to handle your form:
You can make your form point to it using:
The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your
index.html
). You could use Express to also serve static content, likeindex.html
, using theexpress.static
middleware.