Unity Post Request body is empty in server.
I'm trying to make a Post request on Unity to a Node.js server, but it always ends empty. This is my code.
public class variablesValores
{
public int metricaValor { get; set; }
public int X { get; set; }
}
public class StatsScript : MonoBehaviour
{
void Start()
{
var url = "http://localhost:3000/api/variablesValores";
variablesValores variable = new variablesValores ();
variable.metricaValor = 2;
variable.X = 1;
string JSON_Body = JsonUtility.ToJson(variable);
StartCoroutine(PostRequest(url, JSON_Body));
}
IEnumerator PostRequest(string url, string bodyJsonString)
{
var request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(bodyJsonString);
request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.chunkedTransfer = false;
yield return request.SendWebRequest();
Debug.Log("Response: " + request.downloadHandler.text);
}
}
And in the server side I have just a console.log(req.body) that always return empty used with Unity, but that works with Postman.
Comment
Answer by misher · Mar 15, 2019 at 09:22 AM
You are missing this part:
request.uploadHandler.contentType = "application/json";
PS: I've been working on UnityOpenApi project, a unity friendly RESTful API client generator, check it out on github
Your answer
Follow this Question
Related Questions
POST request to RESTful APIs 0 Answers
Passing Values to a Building in Webplayer 0 Answers
Why isn't my code with a restful api in it npt working 0 Answers