Search Unity

  1. Unity 2018.3 is now released.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. We've updated our Terms of Service. Please read our blog post from Unity CTO and Co-Founder Joachim Ante here
    Dismiss Notice
  4. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  5. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice

UnityWebRequst. CORS problem.

Discussion in 'Scripting' started by Nemonymous, Aug 12, 2018.

  1. Nemonymous


    Jul 15, 2016
    Hi! I'm writing a project on Unity3D under WEBGL. The server for the project is written in C # using the HttpListener. Problem: the request reaches the server, but the request body is empty, i.e. .hasEntityBody == false. In the editor and on the Standalone version everything works. On Webgl, the coroutine is infinitely waiting for the SendWebRequest () method. If after the request to close the server (not immediately), the browser displays a message: The request from an outside source is blocked: A single-source policy prohibits reading the remote resource to http: // localhost: 5555 /. (Cause: CORS request failed). The joke is that earlier requests worked in WebGL, but after I finished all the commands, or something else, I do not even know what else I could change there, suddenly everything stopped working. Other methods such as Post and Get also do not work. Example query:
    Code (CSharp):
    1.  IEnumerator TrySendMessage(string message)
    2. {
    3.      RequestData requestData = new RequestData()
    4.      {
    5.          isMailMessage = true,
    6.          mailData = new MailData()
    7.          {
    8.              targetAddress =,
    9.              senderAddress =,
    10.              senderName = nativeCompany.companyName,
    11.              senderPhone = nativeCompany.phoneNumber,
    12.              message = message
    13.          }
    14.      };
    15.      byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(JsonUtility.ToJson(requestData));
    16.      using (UnityWebRequest www = UnityWebRequest.Put("http://localhost:5555", byteArray))
    17.      {
    18.          yield return www.SendWebRequest();
    19.          if (www.isNetworkError || www.isHttpError)
    20.              print(www.error);
    21.          else
    22.          {
    23.              print(www.downloadHandler.text);
    24.              UI.inst.SetMailWindowState(false);
    25.          }
    26.      }
    27. }
    Here's the server:
    Code (CSharp):
    1.  static async Task Listen()
    2.      {
    3.          HttpListener httpListener = new HttpListener();
    4.          httpListener.Prefixes.Add("http://localhost:5555/");
    5.          httpListener.Start();
    6.          Console.WriteLine("Started...");
    7.          while (true)
    8.          {
    9.              HttpListenerContext context = await httpListener.GetContextAsync();
    10.              HttpListenerRequest request = context.Request;
    11.              HttpListenerResponse response = context.Response;
    12.              //response.AddHeader("Access-Control-Allow-Credentials", "true");
    13.              response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time");
    14.              response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONAL");
    15.              response.AddHeader("Access-Control-Allow-Origin", "*");
    16.              Console.WriteLine("New request...");
    17.              if (request.HasEntityBody)
    18.              {
    19.                  Stream stream = response.OutputStream;
    20.                  BinaryWriter binaryWriter = new BinaryWriter(stream);
    21.                  //BinaryReader binaryReader = new BinaryReader(request.InputStream);
    22.                  byte[] byteArray = new byte[request.ContentLength64];
    23.                  request.InputStream.Read(byteArray, 0, (int)request.ContentLength64);
    24.                  RequestData requestData = JsonConvert.DeserializeObject<RequestData>(System.Text.Encoding.UTF8.GetString(byteArray));
    25.                  if (requestData.isDataRequest)
    26.                  {
    27.                      //...
    28.                      binaryWriter.Write("OK");
    29.                  }
    30.                  else if (requestData.isAuthentification)
    31.                  {
    32.                      //...
    33.                      binaryWriter.Write("OK");
    34. ...
    35.                  }
    The server outputs "New request" but does not enter the condition, since the body is empty. There where three points - some operations. Earlier when I wrote the server and there were problems with CORS, the browser in the console displayed in brackets what exactly the problem was, and now it's just a failure of the CORS request... From the browser, only the pre-flight empty Options request is sent, with no answer. Thank you.
  2. Scabbage


    Dec 11, 2014
    That isn't the entire Listen method. Have you printed out request.HasEntityBody before the if block? It could still give no output even if it did enter, if isDataRequest and isAuthentification were false.
  3. Nemonymous


    Jul 15, 2016
    Thank you for your answer!
    Yes, this is not the entire method, because the further code is just other command types in the "else if", such as "isMailSending", "isSomethingElse", etc., and closing the Stream at the end. Yes, of course I checked the value of "hasEntityBody" before checking the type of command. In addition, I wrote that on other platforms everything works.