Skip to content

Instantly share code, notes, and snippets.

@stefek99 stefek99/README.md
Last active Sep 18, 2017

Embed
What would you like to do?
Old answer (removed from StackOverflow)

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 : "xxx@xxx.com"},
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="some@data.xxx"></input>
<input type="submit" value="Send me your name!" id="login-button">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.