Created
April 28, 2016 14:49
-
-
Save philnash/4ce0c0b10ef510f4dc440c3f9d5a24d6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "fetch", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "Phil Nash <[email protected]>", | |
"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