Originally it was here: http://stackoverflow.com/a/11818691/775359
Piece of working code
(I'm sure it will help)
Well... Many things have changes since then and I believe it is worth keeping things up to date :)
Originally it was here: http://stackoverflow.com/a/11818691/775359
Piece of working code
(I'm sure it will help)
Well... Many things have changes since then and I believe it is worth keeping things up to date :)
var express = require('express'); | |
var app = express(); | |
app.use(express.bodyParser()); // Required for parsing POST | |
app.get('/', function(req, res){ | |
res.send('Hello World'); | |
}); | |
app.get('/home', function(req,res){ | |
console.log(__dirname); | |
res.sendfile(__dirname + '/init.html'); | |
}); | |
app.post('/request', function(req, res){ | |
console.log("received POST: app.post('/request', function(req, res){ ... }") | |
console.log("req.param: " + req.param("email")); | |
console.log("req.body: " + req.body); | |
console.log("req: " + req); //[object Object] | |
// TypeError: Converting circular structure to JSON | |
// console.log("req (stringify)" + JSON.stringify(req)) | |
var myResponse = {thank : "you"}; // Received JSON - need reply with JSON | |
res.setHeader("Content-Type", "text/html"); | |
res.write(JSON.stringify(myResponse)); | |
res.end(); | |
console.log("response sent"); | |
}); | |
app.listen(3001); | |
console.log('Listening on port 3001'); |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Init</title> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> | |
<script> | |
$(document).ready(function() { | |
$("#login-button").click(function(event) { | |
email = $("#email").val(); | |
console.log("submitting " + email); | |
event.preventDefault(); | |
//var data = {imie: email}; | |
//console.log(data); | |
$.ajax({ | |
type: 'POST', | |
dataType: 'json', | |
url: 'request', | |
data: {email : "[email protected]"}, | |
beforeSend: function(){console.log("sending: " + this.data);}, | |
success: function(msg) { | |
console.log("success handler"); | |
console.log(msg); | |
}, | |
error:function (xhr, ajaxOptions, thrownError){ | |
console.log(xhr.status); | |
console.log(thrownError); | |
} | |
}); | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<input type="text" id="email" value="[email protected]"></input> | |
<input type="submit" value="Send me your name!" id="login-button"> | |
</body> | |
</html> |