vendredi 27 mars 2015

Can't receive image on node server for xmlhttprequest POST

I want my node server to receive an image via xmlhttprequest() POST method. My server receives the post request, but doesn't show any response. What can i do for displaying the received image file from node server ?


Client side:



function upload(file) {
console.log(file);
var fd = new FormData();
fd.append("image", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/upload",true);
xhr.onload = function(e) {
return console.log("uploading");
};
xhr.setRequestHeader("Content-type","multipart/form-data");
xhr.send(fd);
}


Server side:



var form = new formidable.IncomingForm();

if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
console.log('req method'+req.method);
var form = new formidable.IncomingForm();

form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'multipart/form-data'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}



  • server logs receiving post request on console. But it's not receiving formdata object.

  • No response from xhr.onload() in console. I'm in confusion if xmlhttprequest is working.

  • I've searched through SO, but found most of the asked questions passing text form data.

  • I've to use xmlhttprequest(). I've used formidable to handle formData. Is there any alternative ?


  • AFAIK i've used 'multipart/form-data' encoding. Why browser thinks that as preflighted ? console gives this on client side :


    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/upload. This can be fixed by moving the resource to the same domain or enabling CORS.




Aucun commentaire:

Enregistrer un commentaire