无法发送表单提交的Fetch请求,寻求技术解决方案
异步Fetch请求无响应问题排查与解决方案
问题场景
提交表单时发送异步Fetch请求到api/booking/new无任何响应,怀疑FormData取值环节存在问题,相关代码如下:
原JavaScript代码
const addBooking_form = document.getElementById("form_addResa"); addBooking_form.addEventListener("submit", (event) => { event.preventDefault(); // Send asynchronous request to /api/booking/new const formData = new FormData(addBooking_form); const searchParams = new URLSearchParams(formData); console.log(formData); console.log(searchParams); const asyncReqAdd = fetch("api/booking/new", { method: "POST", body: formData }); asyncReqAdd.then(response => { return console.log(response.text() == 'undefined' ? 'Fetch reponse <=> undefined' : response); }).then((response) => { console.log(response) table.innerHTML = response; }); return console.log('New booking submited'); })
对应HTML表单
<form id="form_addResa"> <div class="fieldset flexCol-around"> <label for="input_lieu">Lieu *</label> <select id="input_lieu" name="place"> <option value="none">< Séléctionner un lieu ></option> <option value="Salammbô">Salammbô</option> <option value="Pergola">Pergola</option> <option value="Salon Jaune">Salon Jaune</option> <option value="1001 Bougies">1001 bougies</option> </select> <div class="flexRow-around"> <div class="flexCol-around"> <label for="input_date">Date *</label> <input id="input_date" type="date" name="date"> </div> <div class="flexCol-around"> <label for="input_time">Heure *</label> <input id="input_time" type="time" name="time"> </div> </div> <label for="input_nom">Nom *</label> <input id="input_nom" type="text" name="name"> <label for="input_prenom">Prénom *</label> <input id="input_prenom" type="text" name="firstName"> </div> <div class="fieldset flexCol-around"> <label for="input_couverts">Nombre de couverts *</label> <input id="input_couverts" type="number" name="coverts"> <label for="input_intExt">Client interne / externe *</label> <select name="intExt" id="input_intExt"> <option value="ext">Externe</option> <option value="int">Interne</option> </select> <label for="input_contacte">Contacter le client *</label> <input id="input_contacte" type="text" placeholder="Numéro de chambre / téléphone / E-mail" name="contact"> </div> <div class="fieldset"> <textarea id="input_note" placeholder="Note :" name="notes"></textarea> </div> <div class="flexRow-around"> <input type="reset" value="Annuler" style="background: white;"> <input type="submit" onclick="unselectBooking();"> </div> </form>
核心问题与解决方案
1. 修复Promise链式调用错误
原代码第一个then返回console.log()(无有效返回值),导致第二个then接收的response为undefined;同时response.text()是异步操作,需正确等待其完成:
asyncReqAdd.then(response => { // 先校验响应状态 if (!response.ok) { throw new Error(`HTTP错误! 状态码: ${response.status}`); } return response.text(); // 返回text()的Promise,供下一个then处理 }).then((responseText) => { console.log('响应内容:', responseText); table.innerHTML = responseText; })
2. 新增错误捕获机制
原代码未处理请求失败场景(网络错误、后端报错等),添加catch块可快速定位问题:
.catch(error => { console.error('请求失败:', error); });
3. 正确查看FormData内容
直接console.log(formData)无法展示内部键值对,需通过以下方式查看:
// 方式1:循环打印所有键值对 for (let [key, value] of formData.entries()) { console.log(`${key}: ${value}`); } // 方式2:转换为普通对象打印 console.log('FormData内容:', Object.fromEntries(formData));
4. 确认请求路径正确性
检查api/booking/new是否为正确相对路径,若当前页面不在根目录下,需改为绝对路径/api/booking/new(开头加斜杠)。
修改后的完整JavaScript代码
const addBooking_form = document.getElementById("form_addResa"); addBooking_form.addEventListener("submit", (event) => { event.preventDefault(); const formData = new FormData(addBooking_form); // 正确打印FormData内容 console.log('FormData内容:', Object.fromEntries(formData)); fetch("/api/booking/new", { // 确保路径正确 method: "POST", body: formData }) .then(response => { if (!response.ok) { throw new Error(`请求失败,状态码: ${response.status}`); } return response.text(); }) .then(responseText => { console.log('响应内容:', responseText); table.innerHTML = responseText; }) .catch(error => { console.error('请求出错:', error); }); console.log('New booking submited'); });
内容的提问来源于stack exchange,提问作者user19878266
相关产品推荐
相关产品推荐

