FormData 从 multipart/form-data 更改为 form-urlencoded?

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

我正在使用当前的javascript到post表单数据

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

expressjs 后端使用 body-parser,设置如下

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

表单数据正在 post 使用 content-typemultipart/form-data; 正确编辑,但根据 body-parser 他们不解析多部分内容。我怎样才能将表单提交更改为 urlencodedjson 两者都可以被后端解析?

尝试添加一个header请求并将数据转换为url-encode格式

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