Search Unity

  1. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    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. Let us know a bit about your interests, and if you'd like to become more directly involved. Take our survey!
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  5. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

UnityWebRequst. CORS problem.

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

  1. Nemonymous

    Nemonymous

    Joined:
    Jul 15, 2016
    Posts:
    2
    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 = selectedCompanyData.email,
    9.              senderAddress = nativeCompany.email,
    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

    Scabbage

    Joined:
    Dec 11, 2014
    Posts:
    266
    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

    Nemonymous

    Joined:
    Jul 15, 2016
    Posts:
    2
    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.