gpt4 book ai didi

c# - UnityWebRequest.downloadHandler 返回 null,同时从 Node 服务器获取响应

转载 作者:IT老高 更新时间:2023-10-28 13:26:03 28 4
gpt4 key购买 nike

我正在 Unity 上创建一个注册场景。在后端,我有带有 MongoDB 的 NodeJS 服务器。注册成功,数据也保存在 Mongo 上。

这是我用于注册

的NodeJS api
api.post('/register', (req,res) => {
Account.register(new Account({username: req.body.username}), req.body.password, function(err, account){
console.log("acc: "+account);
if(err){
if (err.name == "UserExistsError") {
console.log("User Exists");
return res.status(409).send(err);
}else {
console.log("User Error 500");
return res.status(500).send(err);
}
}else {
let newUser = new User();
newUser.accountid = account._id;
newUser.name = req.body.fullname;
newUser.gender = req.body.gender;
newUser.role = req.body.role;
newUser.country = req.body.country;
newUser.coins = req.body.coins;
newUser.save(err => {
if(err){
console.log(err);
return res.send(err);
}else{
console.log('user saved');
res.json({ message: 'User saved' });
}
});
passport.authenticate(
'local', {
session: false
})(req,res, () => {
res.json({ registermsg: 'Successfully created new account'});
});
}
});
});

这是我在 Unity C# 中的 POST 协程

IEnumerator Post(string b) {

byte[] bytes = System.Text.Encoding.ASCII.GetBytes(b);

using (UnityWebRequest www = new UnityWebRequest(BASE_URL, UnityWebRequest.kHttpVerbPOST)) {
UploadHandlerRaw uH = new UploadHandlerRaw(bytes);
www.uploadHandler = uH;
www.SetRequestHeader("Content-Type", "application/json");
yield return www.Send();

if (www.isError) {
Debug.Log(www.error);
} else {
lbltext.text = "User Registered";
Debug.Log(www.ToString());
Debug.Log(www.downloadHandler.text);
}
}
}

我正在尝试 Debug.Log(www.downloadHandler.text); 但我得到 NullReferenceException

我想问一下,我用来在我的 api 中返回响应的方式是否正确?如果是,我如何在 Unity 端使用该响应。

最佳答案

UnityWebRequest.PostUnityWebRequest.Get 和其他UnityWebRequest functions创建 UnityWebRequest 的新实例,将自动附加 DownloadHandlerBuffer

现在,如果您使用 UnityWebRequest 创建 UnityWebRequest 的新实例构造函数,DownloadHandler 附加到该新实例。您必须使用 DownloadHandlerBuffer 手动执行此操作.

IEnumerator Post(string b)
{

byte[] bytes = System.Text.Encoding.ASCII.GetBytes(b);

using (UnityWebRequest www = new UnityWebRequest(BASE_URL, UnityWebRequest.kHttpVerbPOST))
{
UploadHandlerRaw uH = new UploadHandlerRaw(bytes);
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();

www.uploadHandler = uH;
www.downloadHandler = dH;
www.SetRequestHeader("Content-Type", "application/json");
yield return www.Send();

if (www.isError)
{
Debug.Log(www.error);
}
else
{
lbltext.text = "User Registered";
Debug.Log(www.ToString());
Debug.Log(www.downloadHandler.text);
}
}
}

关于c# - UnityWebRequest.downloadHandler 返回 null,同时从 Node 服务器获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43292700/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com