Skip to content

Instantly share code, notes, and snippets.

@stefek99
Last active September 18, 2017 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stefek99/b10ed037d2a4a323d638 to your computer and use it in GitHub Desktop.
Save stefek99/b10ed037d2a4a323d638 to your computer and use it in GitHub Desktop.
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