简体   繁体   English

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

[英]FormData change from multipart/form-data to form-urlencoded?

I am using the current javascript to post form data 我正在使用当前的JavaScript发布表单数据

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 使用带有body-parserexpressjs后端并进行以下设置

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

The form data is being posted properly with content-type to multipart/form-data; 表单数据已正确地以content-typemultipart/form-data; but according to body-parser they don't parse multipart content. 但根据body-parser的分析,它们不会解析多部分内容。 How can i change the form submission to either urlencoded or json both of which can be parsed by the backend ? 我如何将表单提交更改为urlencodedjson都可以由后端解析?

Try add a header to request and convert data to url-encode format 尝试添加标题以请求并将数据转换为url编码格式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 FormData如何在多部分/表单数据中获取或设置边界 - Angular - FormData how to get or set boundary in multipart/form-data - Angular PHP-从jQuery解析FormData时,multipart / form-data变量返回NULL(AJAX) - PHP - multipart/form-data variables returns NULL when parsing a FormData from jQuery (AJAX) XMLHttpRequest JSON Post以表单编码形式发送 - XMLHttpRequest JSON Post going as form-urlencoded 使用ajax jquery时出现奇怪的“ urlencoded”和“ multipart / form-data”内容 - strange “urlencoded” and “multipart/form-data” content when using ajax jquery 带iframe的多部分/表单数据 - Multipart/form-data with iframe application/x-www-form-urlencoded 和 multipart/form-data 是客户端向服务器发送数据时唯一处理的两种特殊内容类型吗? - Are application/x-www-form-urlencoded and multipart/form-data the only 2 special content types treated by the client when sending data to server? JS FormData 将文件作为应用程序/ocet-stream 发送,如何将其设置为 multipart/form-data? - JS FormData sends file as application/ocet-stream, how to set it as multipart/form-data? 没有字段名称的多部分/表单数据表单 - multipart/form-data form with no field names 角度多部分/表单数据表单发送 - Angular multipart/form-data form sending 如何将文件系统中的文件编码为multipart / form-data? - How to encode a file from the file system as multipart/form-data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM