我正在Unity上创建一个注册场景。在后端,我使用NodeJS服务器和MongoDB。注册成功后,数据也保存在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中使用该响应。
DownloadHandlerBuffer
感到困惑。但现在我遇到了Can't send headers after they are set.
的问题。我阅读了很多问题,但无法使我的代码按照它们的要求工作。 - Luzan BaralUnityWebRequest
的新实例时,DownloadHandlerBuffer
未被附加。如果你使用UnityWebRequest.Post
或UnityWebRequest.Get
函数创建UnityWebRequest
的新实例,这些函数将自动将DownloadHandlerBuffer
附加到它上面,因为90%的情况下,人们需要在Get/Post请求中访问服务器数据。 - ProgrammerDownloadHandlerBuffer
附加到UnityWebRequest
上?如果您想在数据仍在接收时流式传输或访问数据,为什么要让Unity附加DownloadHandlerBuffer
?它在这里完全没有用处,需要使用DownloadHandlerScript
而不是DownloadHandlerBuffer
。 - ProgrammerDownloadHandlerTexture
进行纹理解压缩的时候附加DownloadHandlerBuffer
?这并不是因为创建新的UnityWebRequest实例意味着您正在进行自定义操作,因此您需要编写更多的代码。 Unity希望给您控制权。我相信还有许多其他原因。 - Programmer