Search Unity

Bug UnityWebRequest missing headers in WebGL

Discussion in 'Scripting' started by kiamvdd, Aug 17, 2021.

  1. kiamvdd

    kiamvdd

    Joined:
    Sep 30, 2016
    Posts:
    16
    We have a multiplatform game that on some platforms makes use of a backend to fetch parameters for our game, as well as tracking when the game begins and ends.

    Up until recently, our WebGL platform did not require this back end to fetch parameters. In an effort to align some of our platforms more closely however, we are in the process of updating our WebGL platform to make use of the back end in the same way that our stand alone application does.

    We noticed however that in our get requests, many headers seem to be missing. This is a problem because we depend on custom headers to verify that we have valid parameters being returned by the API. These headers, along with various standard headers, are nowhere to be found when calling UnityWebRequest.GetResponseHeaders, even though the body is completely intact. Checking the networking tab in the browser developer tools shows that the request is complete and includes all expected headers. Likewise, when doing the same request from a stand alone build, all expected headers show up

    To confirm that this is not an issue with our own API, I have also tested this using https://mockbin.org to set up a mock endpoint with a custom header, and found the same result there. Here is what I did to print out the headers:


    Code (CSharp):
    1.     public void SendRequest()
    2.     {
    3.         var request = UnityWebRequest.Get(_inputField.text);
    4.         var response = request.SendWebRequest();
    5.         response.completed += op => PrintRequestHeaders(response.webRequest);
    6.     }
    7.  
    8.     private void PrintRequestHeaders(UnityWebRequest request)
    9.     {
    10.         Debug.Log("UnityWebRequest headers: \n" + string.Join(" | ", request.GetResponseHeaders().Keys));
    11.     }

    As this seems to be a WebGL specific issue, is there any way we can fix this or work around this? We are currently using 2019.4.20f1.
     
  2. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    1,066
    With WebGL you are running in a browser and therefore all browser restrictions regarding sending and receiving http requests apply. Specifically, unless you're making a simple or same-origin request, CORS rules prevent you from accessing any response headers besides a few basic ones.

    You'll have to either disable CORS by sending the right
    Access-Control-Allow-Origin
    header or explicitly allow the headers you need by sending
    Access-Control-Expose-Headers
    .

    Generally, reading up on CORS and all of its rules is really important whenever you try to send any non-trivial request in a browser.
     
    AminAghajoon and Bunny83 like this.