表单数据传入JS获取API认证Token故障求助
问题排查与代码修正
核心错误点分析
HTML输入框属性语法错误
两个输入框的value属性写法有误,正确格式应为value="",原代码中少了等号,会导致浏览器无法正确解析输入框的初始值设置,可能间接影响值的获取。JavaScript获取表单值的逻辑错误
- 错误地将DOM查询代码用字符串包裹(如
"document.getElementById('email')"),导致传递给API的是这段字符串而非用户输入的邮箱/密码。 - 使用了错误的元素ID:输入框实际ID是
emailresultsapp和pwdresultsapp,但代码中用了email和pwd,无法定位到正确的元素。 - 未获取输入框的
value属性:即使正确获取DOM元素,也需要通过.value才能拿到用户输入的内容,否则传递的是DOM对象本身。
- 错误地将DOM查询代码用字符串包裹(如
调试信息缺失
fetch回调中的console.log()未传入参数,无法查看API返回的结果,难以排查认证失败的具体原因。
修正后的完整代码
<form id="apiauth"> <label for="email">Email:</label> <input type="email" id="emailresultsapp" name="email" value=""> <label for="pwd">Password:</label> <input type="password" id="pwdresultsapp" name="pwd" value=""> <input type="button" value="Submit" onclick="authenticate()"> </form> <input type="button" value="Generate a table" onclick="generateTable()" /> <script> function authenticate (){ // 正确获取输入框的value值 const email = document.getElementById('emailresultsapp').value; const password = document.getElementById('pwdresultsapp').value; var formdata = new FormData(); formdata.append("username", email); formdata.append("password", password); var requestOptions = { method: 'POST', body: formdata, redirect: 'follow' }; fetch("URL", requestOptions) .then(response => response.text()) .then(result => { // 添加调试日志,查看API返回结果 console.log('API返回结果:', result); getresults(result, parseJwt(result).username); }) .catch(error => console.log('error', error)); } function parseJwt (token) { var base64Url = token.split('.')[1]; var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); return JSON.parse(jsonPayload); }; function getresults (token, userid){ generateTable(); } function generateTable() { const tbl = document.createElement("table"); const tblBody = document.createElement("tbody"); for (let i = 0; i < 2; i++) { const row = document.createElement("tr"); for (let j = 0; j < 2; j++) { const cell = document.createElement("td"); const cellText = document.createTextNode(`cell in row ${i}, column ${j}`); cell.appendChild(cellText); row.appendChild(cell); } tblBody.appendChild(row); } tbl.appendChild(tblBody); document.body.appendChild(tbl); tbl.setAttribute("border", "2"); } </script>
额外优化建议
- 可以改用表单的
submit事件监听替代按钮的onclick,同时调用event.preventDefault()阻止表单默认提交行为,代码更符合现代前端规范:
document.getElementById('apiauth').addEventListener('submit', function(event) { event.preventDefault(); authenticate(); });
然后将按钮类型改为submit:<input type="submit" value="Submit">
内容的提问来源于stack exchange,提问作者Chesney
相关产品推荐
相关产品推荐

