如何修复Uncaught (in promise) SyntaxError: Unexpected end of input错误?
提交登录表单时触发Promise语法错误的问题排查与修复
提交userid、password、usertype表单时,总会触发Uncaught (in promise) SyntaxError: Unexpected end of input错误,错误位于代码的72、73行。以下是完整代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Fetch API Sandbox</title> </head> <body> <h1>Fetch API Sandbox</h1> <button id="getUsers">Get JSON</button> <div id="output"></div> <!--Hier wird das JSON reingeschrieben--> <form id="addPost"> <div> <input type="text" id="userid" placeholder="userID"> </div> <div> <input type="text" id="password" placeholder="password"> </div> <div> <input type="text" id="usertype" placeholder="userType"> </div> <input type="submit" value="Submit"> </form> <script> document.getElementById('getUsers').addEventListener('click', getUsers); document.getElementById('addPost').addEventListener('submit', addPost); function getUsers() { fetch('https://192.168.50.34:9004/v1/login',{mode: "no-cors"}) .then(function(response) { if (response.ok) return response.json(); else throw new Error("Names could not be loaded!") }) .then(function(json) { console.log(json); let output = '<h2>Users</h2>'; json.forEach(function(user) { output += ` <ul> <li>userID: ${user.userid}</li> <li>password: ${user.password}</li> <li>userType: ${user.usertype}</li> </ul> `; console.log(output); document.getElementById("output").innerHTML = output; }); }) } function addPost(e) { e.preventDefault(); let userId = document.getElementById('userid').value; //console.log(id); let password = document.getElementById('password').value; let userType = document.getElementById('usertype').value; fetch('https://192.168.50.34:9004/v1/login', { method: 'POST', mode: 'no-cors', headers: { 'Accept': 'application/json,', 'Content-type': 'application/json' }, body: { userId: userId, password: password, userType: userType } }) .then((res) => res.json()) .then((data) => console.log(data)) } </script> </body> </html>
错误来源代码段
经测试,错误来自以下代码:
.then((res) => res.json()) .then((data) => console.log(data))
这两行代码的作用:
- 第一行
res.json():将服务器返回的响应内容解析为JSON格式的JavaScript对象,这个操作本身返回一个Promise - 第二行:接收上一步解析完成的JSON数据,并打印到控制台
控制台错误信息
Uncaught (in promise) SyntaxError: Unexpected end of input (at index.html:72:22) at index.html:72:22 (anonymous) @ index.html:72 Promise.then (async) addPost @ index.html:73
服务器预期响应格式(Postman测试结果)
{ "Result": { "ResultCode": 0 }, "AccountInfo": { "UserID": 1000000000000000000, "UniqueID": "", "Uuid": "xxxx-xxxx-xxxx-xxxx", "Name": "xxxx", "LoginPW": "", "Privilege": 1, "FirstLoginFlag": 0, "ServerID": 11, "LoginAllowed": 1, "LoginFailCount": 0, "WebLogin": 1, "VisitLogin": 0, "LoginIP": "", "LoginTime": "2022-12-21 12:45:56", "LastLoginIP": "", "LastLoginTime": "2022-12-21 12:08:12" }, "SystemInfo": { "Version": "1.1.17.0", "LicenseLevel": 40, "LicenseStatus": 0, "BrandType": 1, "TimezoneVersion": 0, "HTTPSFlag": 1, "SiteName": "", "SiteLogo": "", "SiteMessageWarning": "", "DeviceServerVersion": 10 }, "LoginFailInfo": { "RemindCount": 0 } }
问题修复与解释
1. 核心问题:mode: 'no-cors'
当使用no-cors模式时,浏览器会屏蔽服务器返回的响应内容,导致res.json()无法获取到任何有效数据,自然会抛出"Unexpected end of input"错误。解决方式:
- 去掉
mode: 'no-cors'配置,确保服务器已正确配置CORS(允许前端域名跨域请求)
2. 请求body格式错误
fetch的body参数不能直接传入JavaScript对象,必须转换为JSON字符串,否则服务器无法解析。需要用JSON.stringify()包装:
body: JSON.stringify({ userId: userId, password: password, userType: userType })
3. 请求头语法错误
Accept头末尾多了一个逗号,会导致请求头格式无效,去掉即可:
headers: { 'Accept': 'application/json', 'Content-type': 'application/json' }
4. 缺少错误捕获机制
Promise链式调用中如果发生错误,需要用.catch()捕获并处理,避免错误抛到控制台:
fetch(...) .then((res) => res.json()) .then((data) => console.log(data)) .catch((err) => console.error('请求错误:', err))
Promise工作机制简单说明
fetch函数会返回一个Promise对象,它代表异步操作的最终完成或失败:
.then()方法用于指定异步操作成功时的回调函数,上一个.then()的返回值会作为下一个.then()的参数.catch()方法用于捕获链式调用中任何环节发生的错误res.json()是异步操作,所以它也返回Promise,必须通过.then()才能拿到解析后的JSON数据
修复后的完整addPost函数:
function addPost(e) { e.preventDefault(); let userId = document.getElementById('userid').value; let password = document.getElementById('password').value; let userType = document.getElementById('usertype').value; fetch('https://192.168.50.34:9004/v1/login', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-type': 'application/json' }, body: JSON.stringify({ userId: userId, password: password, userType: userType }) }) .then((res) => { // 先检查响应状态是否正常 if (!res.ok) throw new Error(`HTTP错误,状态码:${res.status}`); return res.json(); }) .then((data) => console.log(data)) .catch((err) => console.error('登录请求失败:', err)) }
内容的提问来源于stack exchange,提问作者Einsiful
相关产品推荐
相关产品推荐

