UnityWebRequest.downloadHandler返回空值,当从Node服务器获取响应时。

8

我正在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中使用该响应。
2个回答

14

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

但是,如果你使用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);
        }
    }
}

谢谢,我对使用DownloadHandlerBuffer感到困惑。但现在我遇到了Can't send headers after they are set.的问题。我阅读了很多问题,但无法使我的代码按照它们的要求工作。 - Luzan Baral
也许这个可以解决你的问题?我会离开几个小时,回来之前无法回复。 - Programmer
1
@Evorlor 我不知道什么是“null构造函数”,我只谈到了构造函数而已,当你像通常一样使用其构造函数创建UnityWebRequest的新实例时,DownloadHandlerBuffer未被附加。如果你使用UnityWebRequest.PostUnityWebRequest.Get函数创建UnityWebRequest的新实例,这些函数将自动将DownloadHandlerBuffer附加到它上面,因为90%的情况下,人们需要在Get/Post请求中访问服务器数据。 - Programmer
1
如果您只想发出请求,但不关心数据发送者发送的数据,为什么要将DownloadHandlerBuffer附加到UnityWebRequest上?如果您想在数据仍在接收时流式传输或访问数据,为什么要让Unity附加DownloadHandlerBuffer?它在这里完全没有用处,需要使用DownloadHandlerScript而不是DownloadHandlerBuffer - Programmer
1
如果您想高效地下载纹理,为什么Unity需要在需要使用DownloadHandlerTexture进行纹理解压缩的时候附加DownloadHandlerBuffer?这并不是因为创建新的UnityWebRequest实例意味着您正在进行自定义操作,因此您需要编写更多的代码。 Unity希望给您控制权。我相信还有许多其他原因。 - Programmer
显示剩余7条评论

1
你只需要附加一个DownloadHandlerBuffer,不需要新建UnityWebRequest! DownloadHandlerBuffer dH = new DownloadHandlerBuffer(); www.downloadHandler = dH;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接