我正在嘗試將我的 Unity 游戲連接到我的網路服務器。我使用 vue 應用程式很好地連接到服務器,并在 Postman 中測驗了端點,它們都運行良好。但是,當我從 Unity 發送具有相同資訊的 JSON 時,當我在服務器路由中調出 req.body 時,它看起來是一樣的。雖然當我得到電子郵件的長度時,它們是不同的。[email protected] 的長度為 13,但是當我使用 Unity 發送時,它的長度為 14。它總是添加一個額外的字符(長度)。
登錄資料.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class LoginData
{
public string username;
public string password;
}
發送資料.cs
public void SendLogin()
{
StartCoroutine(Login());
}
private IEnumerator Login()
{
var email = loginEmail.text;
var password = loginPassword.text;
var loginData = new LoginData();
loginData.username = loginEmail.text;
loginData.password = loginPassword.text;
var json = JsonUtility.ToJson(loginData);
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;
}
}
Postman 的服務器輸出
req.body = { username: '[email protected]', password: 'test' }
req.body.username.length = 13
Unity 的服務器輸出
req.body = { username: '[email protected]?', password: 'test?' }
req.body.username.length = 14
服務器登錄路由
router.post('/login', async (req, res, next) => {
let username = req.body.username;
console.log('req.body = ' req.body);
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(req.body.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.')
}
})
});
uj5u.com熱心網友回復:
鑒于您提供的代碼和非常小的 Node 服務器,我無法重現您描述的問題。
我建議您在手動硬編碼登錄資料中的用戶名/密碼值時檢查問題是否仍然存在。我懷疑輸入欄位正在添加一個奇怪的額外無長度空白字符(或類似的東西),或者您的問題實際上不是在客戶端和服務器之間,而是您首先編碼的實際值。
您還應該檢查并確認您的服務器如何處理正文決議,但如果 Postman 的請求確實正常,我會懷疑它設定正確。在下面的示例中,我使用了body-parser運行良好的包。
服務器輸出:
Example app listening on port 3000
username.length: 13
{ username: '[email protected]', password: 'pasword' }
示例節點服務器:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000
const jsonParser = bodyParser.json()
app.use(jsonParser)
app.get('/', (req, res) => {
res.send('Hello World!')
});
app.post('/login', (req, res) => {
const { username, password } = req.body
console.log(`username.length: ${username.length}`)
console.log({
username,
password
})
res.send({ message: 'success' })
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
});
統一腳本:
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
[Serializable]
public class LoginData
{
public string username;
public string password;
}
public class WebRequestTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
StartCoroutine(SendRequest());
}
private IEnumerator SendRequest()
{
var loginUrl = "http://localhost:3000/login";
var loginData = new LoginData();
loginData.username = "[email protected]";
loginData.password = "pasword";
var json = JsonUtility.ToJson(loginData);
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;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/524490.html
