Skip to content

Instantly share code, notes, and snippets.

@wrpinheiro
Created February 5, 2017 23:25
Show Gist options
  • Save wrpinheiro/c2ea5a0c702d90c2bcdc919d458c9748 to your computer and use it in GitHub Desktop.
Save wrpinheiro/c2ea5a0c702d90c2bcdc919d458c9748 to your computer and use it in GitHub Desktop.
Example of how to use the Formidable package to parse Formdata in a Node.js application
<!DOCTYPE html>
<html>
<head>
<title>FormData, Node and Formidable Example</title>
</head>
<body>
<button onClick="buttonClicked()">Click me</button>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" charset="utf-8" async defer>
var formData = new FormData();
formData.append('first_name', 'joseph');
formData.append('last_name', 'klimber');
function buttonClicked() {
$.ajax ({
url: 'http://localhost:3000',
method: 'POST',
contentType: false,
data: formData,
processData: false,
success: function(data) {
alert(data);
console.log(data);
}
});
}
</script>
</body>
</html>
var express = require('express');
var formidable = require('formidable');
var app = express();
app.use(express.static('public'));
app.post('/', function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, (err, fields, files) => {
var name = fields.first_name + ' ' + fields.last_name;
res.send(`Hello ${name}!`);
});
});
app.listen(3000, function () {
console.log('App listening on port 3000');
});
{
"name": "formdata-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"express": "^4.14.1",
"formidable": "^1.1.1"
},
"devDependencies": {},
"scripts": {
"start": "node index"
},
"author": "",
"license": "ISC"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment