Reputation: 11
Key-value pairs like name
are appended to form-data in a client-side XMLHttpRequest
and sent with file to be uploaded.
How can I extract those values on the server side, which is using Node.js.
Browser:
formdata = new FormData();
for( var x = 0;x < files.length;x = x+1){
formdata.append('file',files[x]);
}
formdata.append('name',name); //name appended here to form-data
formdata.append('email',email);
formdata.append('reason',reason);
formdata.append('location',location);
var xhr = new XMLHttpRequest();
var url = "/sign_8081";
xhr.open("POST" ,url);
xhr.withCredentials = true;
Node.js Server:
router.post('/sign_8081', (req, res) => {
console.log("sign 8081called"+JSON.stringify(req.body))
console.log(req.query.name);
console.log(req.body.name); //want name key value in Node.js code
let body = '';
var rb;
req.on('data', chunk => {
body += chunk.toString(); // convert Buffer to string
});
req.on('end', () => {
rb = parse(body)
console.log(rb.name);
});
console.log(req.file.filename)
res.send(req.file.filename)
});
Upvotes: 1
Views: 3428
Reputation: 1483
If you are using expressjs, use body-parsing middlewares such as express.json()
or express.urlencoded()
, then your can access form input req.body
.
var app = express()
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x- www-form-urlencoded
router.post('/sign_8081', (req, res) => {
console.log("sign 8081called"+JSON.stringify(req.body))
console.log(req.query.name);// do not use this
console.log(req.body); // object of inputs
let body = '';
var rb;
req.on('data', chunk => {
body += chunk.toString(); // convert Buffer to string
});
req.on('end', () => {
rb = parse(body)
console.log(rb.name);
});
console.log(req.file.filename)
res.send(req.file.filename)
});
For more on expressjs request object expressjs docs
Upvotes: 1