Unity向Node.js服务器发送JSON时字符长度异常问题
问题诊断
从服务器输出的字符串能明显看到,Unity发送的username和password末尾带有不可见的空白/零宽字符,这就是导致字符串长度多1的核心原因。大概率是Unity UI输入框(loginEmail、loginPassword)的文本中混入了用户输入时误加的换行、空格,或是输入框组件本身的格式残留问题。
解决方案
最直接的解决方式是从客户端源头清理无效字符,在Unity端对输入文本做首尾空白去除处理,同时添加调试日志确认处理结果。如果需要也可在服务器端添加兜底逻辑。
修改后的Unity代码(SendData.cs)
public void SendLogin() { StartCoroutine(Login()); } private IEnumerator Login() { // 清理输入文本首尾的空白、换行等不可见字符 var email = loginEmail.text.Trim(); var password = loginPassword.text.Trim(); var loginData = new LoginData(); loginData.username = email; loginData.password = password; var json = JsonUtility.ToJson(loginData); // 调试用:打印处理后的内容和长度,确认是否正常 Debug.Log($"序列化后的JSON: {json}"); Debug.Log($"清理后username长度: {email.Length}"); using UnityWebRequest webRequest = new UnityWebRequest(loginUrl, "POST"); webRequest.SetRequestHeader("Content-Type", "application/json; charset=utf-8"); byte[] rawJson = System.Text.Encoding.UTF8.GetBytes(json); webRequest.uploadHandler = new UploadHandlerRaw(rawJson); webRequest.downloadHandler = new DownloadHandlerBuffer(); yield return webRequest.SendWebRequest(); switch(webRequest.result) { case UnityWebRequest.Result.InProgress: Debug.Log("In Progress..."); break; case UnityWebRequest.Result.Success: Debug.Log(webRequest.downloadHandler.text); break; case UnityWebRequest.Result.ConnectionError: Debug.Log("Connection Error..."); break; case UnityWebRequest.Result.ProtocolError: Debug.Log("Protocol Error..."); break; case UnityWebRequest.Result.DataProcessingError: Debug.Log("Data Processing Error..."); break; default: Debug.Log("Default..."); break; } }
服务器端兜底方案(可选)
如果客户端处理后仍有异常,可在服务器路由中添加字符清理逻辑:
router.post('/login', async (req, res, next) => { // 服务器端兜底清理首尾空白 let username = req.body.username.trim(); let password = req.body.password.trim(); console.log('req.body = ' + JSON.stringify({username, password})); console.log('req.body.username.length = ' + username.length); User.findOne({email: username}) .then(async(user) => { if(!user) { console.log('not found'); return res.status(401).send('Invalid Credentials.') } if (user.failedLoginAttempts >= allowedFailedLoginAttempts) { return res.status(401).send('Account Locked.') } const isValidPassword = await GSUtility.isValidPassword(password, user.password) if (isValidPassword) { console.log('good'); const jwt = GSUtility.issueJWT(user); user.updateLogin(); return res.status(200).send({ user: user, token: jwt.token, expires: jwt.expires }) } else { user.increaseFailedLoginAttempts(); console.log('bad info'); return res.status(401).send('Invalid Credentials.') } }) });
内容的提问来源于stack exchange,提问作者K.G
相关产品推荐
相关产品推荐

