简体   繁体   中英

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 ?

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)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM