Reputation: 676
I want to send a blob data from JA client to NodeJS server.
Now I have this client-side code: [...] recorder.exportWAV(function(blob) { audioObj = blob; });
var formData = new FormData();
formData.append("operation", "addMessage");
formData.append("msg", audioObj);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/sendRecord", true);
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status==200){
// get response from server
}
}
xhr.send(formData);
I use some JS library to record audio from integrated microphone, and at the end I have a audioObj that is a blob object.
And this si node.js server that I want to adjust for receiving data.
var http = require('http'),
url = require('url');
var app = http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
// check the url path
if (path == "/sendRecord") {
// check the request method
if(request.method != "POST"){
// return error
}
// _______________________________
//| here I want catching XHR data |
// –––––––––––––––––––––––––––––––
}
}).listen(8080);
console.log("Server running on: http://localhost:8080/");
I think should be some server-side XHR API for responding to the client XHR request, but I don't know which and where to find they. Could anyone help me? also whit link or documentation... ;)
Thanks!
Upvotes: 2
Views: 3225
Reputation: 676
I answer to myself... If anyone find useful in future ;)
Using Formidable (https://github.com/felixge/node-formidable) I've done this:
var http = require('http'),
url = require('url'),
formidable = require('formidable')
util = require('util');
var server = http.createServer().listen(8080);
server.on('request', function(request, response) {
var form = new formidable.IncomingForm(),
fields = [],
files = [];
form.on('error', function(err){
response.writeHead(200, {'content-type': 'text/plain'});
response.end('error:\n\n' + util.inspect(err));
});
form.on('field', function(field, value){
console.log(field, value);
fields.push([field, value]);
});
form.on('file', function(field, file){
console.log(field, file);
files.push([field, file]);
});
form.on('end', function(){
console.log('-> upload done');
response.writeHead(200, {'content-type': 'text/plain'});
response.write('Received fields:\n\n ' + util.inspect(fields));
response.write('\n\n');
response.end('received files:\n\n ' + util.inspect(files));
});
form.encoding = 'utf-8';
form.uploadDir = './tmp';
form.keepExtensions = true;
form.parse(request);
});
Thanks to robertklep for the suggestion!
Upvotes: 3