royb royb - 4 months ago 11
Node.js Question

Node.js - How to send data from html to express

this is form example in html:

<!DOCTYPE html>
<meta charset="utf-8" />
<title>CSS3 Contact Form</title>
<div id="contact">
<h1>Send an email</h1>
<form action="/myaction" method="post">
<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" />


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':
sys.puts('Server running at');

I have 2 questions:

  1. How can I call
    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")

  2. In the node.js function where I put "?????" how can I get data from the html form.
    When I type I don't get the data...


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:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());'/myaction', function(req, res) {
  res.send('You sent the name "' + + '".');

app.listen(8080, function() {
  console.log('Server running at');

You can make your form point to it using:

<form action="" method="post">

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, like index.html, using the express.static middleware.