Search code examples
javascriptnode.jsajaxmultipartform-dataform-data

FormData change from multipart/form-data to form-urlencoded?


I am using the current javascript to post form data

var request = new XMLHttpRequest();
request.open("POST", "/validate",false);
request.send(new FormData(form));  // form is document.getElementById("#form")

With an expressjs backend using body-parser with following settings

app.use(parser.urlencoded({ extended: false }));

The form data is being posted properly with content-type to multipart/form-data; but according to body-parser they don't parse multipart content. How can i change the form submission to either urlencoded or json both of which can be parsed by the backend ?


Solution

  • Try add a header to request and convert data to url-encode format

    function urlencodeFormData(fd){
        var s = '';
        function encode(s){ return encodeURIComponent(s).replace(/%20/g,'+'); }
        for(var pair of fd.entries()){
            if(typeof pair[1]=='string'){
                s += (s?'&':'') + encode(pair[0])+'='+encode(pair[1]);
            }
        }
        return s;
    }
    var request = new XMLHttpRequest();
    request.open('POST', '/validate', false);
    request.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
    request.send(urlencodeFormData(new FormData(form)));