Skip to content

Instantly share code, notes, and snippets.

@philnash
Created April 28, 2016 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philnash/4ce0c0b10ef510f4dc440c3f9d5a24d6 to your computer and use it in GitHub Desktop.
Save philnash/4ce0c0b10ef510f4dc440c3f9d5a24d6 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Fetch test</title>
</head>
<body>
<main>
<h1>Press this button</h1>
<button id="btn">Press me</button>
</main>
<script>
var button = document.getElementById("btn");
button.addEventListener("click", function(event){
var formData = new FormData();
formData.append("test", "woohoo");
formData.append("foo", "bar");
formData.forEach(function(key, value) {
console.log(`${key}: ${value}`);
});
fetch("/fetch", {
method: "POST",
body: formData
}).then(function(response) {
return response.json();
}).then(function(json) {
console.log(json);
}).catch(function(err) {
console.log(err);
});
});
</script>
</body>
</html>
var fs = require("fs");
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function(req, res) {
fs.readFile(__dirname + '/index.html', 'utf8', function(err, text){
res.send(text);
});
});
app.post("/fetch", function(req, res) {
console.log(req.body);
res.send(JSON.stringify(req.body));
});
app.listen(3000, function(){
console.log("Your application is listening on localhost:3000");
});
{
"name": "fetch",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Phil Nash <philnash@twilio.com>",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.0",
"express": "^4.13.4"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment