使用Fetch请求通过FormData传递HTML内容失败问题求助
FormData附加HTML内容导致Fetch请求失败的排查与解决
问题描述
我尝试通过Fetch请求,利用FormData对象传递HTML表格数据。以下代码可以正常运行:
let formData = new FormData(); formData.append('sponsor', "My sponsor"); formData.append('rider', "xRider");
但当尝试附加HTML内容时,Fetch请求直接失败:
formData.append('delegation', "<b>Bold Text</b>");
完整请求代码如下:
fetch(request_url, { method: 'POST', processData: false, contentType: false, body: formData }) .then(response => { if (response.ok) return response.json(); }) .then(response => { let response_status = response['status'] == 'success' ? 'success' : 'failed'; // 请求成功时调用sendResponse Console.log("Working correctly") }) .catch(error => { // 请求出错时调用回调函数 call_back_function({ status: "failed", data: error }); console.log('%c View Visa Details Catch Error: ', 'background: #000; color: #bada55', error) });
问题排查与解决
移除Fetch不支持的配置项
processData和contentType是jQuery.ajax的专属配置参数,Fetch API并不识别这两个选项。当使用FormData作为请求体时,浏览器会自动设置正确的Content-Type: multipart/form-data请求头,手动设置反而会导致请求格式异常。修正代码中的大小写错误
原代码里的Console.log是大写开头,正确写法是console.log,这个错误会导致代码执行报错,直接进入catch块。确保HTML内容传递正确
不需要对HTML标签进行实体转义(比如<),直接传递原始HTML字符串即可,后端会正常接收并处理。
修改后的完整代码
let formData = new FormData(); formData.append('sponsor', "My sponsor"); formData.append('rider', "xRider"); formData.append('delegation', "<b>Bold Text</b>"); fetch(request_url, { method: 'POST', body: formData }) .then(response => { if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } return response.json(); }) .then(response => { let response_status = response.status === 'success' ? 'success' : 'failed'; console.log("请求正常执行"); }) .catch(error => { call_back_function({ status: "failed", data: error.message }); console.log('%c View Visa Details Catch Error: ', 'background: #000; color: #bada55', error); });
额外建议
如果修改后仍失败,需要检查后端是否正确配置了multipart/form-data格式的请求解析,确保后端能正确读取FormData中的HTML内容字段。
内容的提问来源于stack exchange,提问作者Jawad Nasar Shah
相关产品推荐
相关产品推荐

