AngularJS performs an OPTIONS HTTP request for a cross-origin resource

后端 未结 14 1662
生来不讨喜
生来不讨喜 2020-11-22 03:04

I\'m trying to setup AngularJS to communicate with a cross-origin resource where the asset host which delivers my template files is on a different domain and therefore the X

14条回答
  •  深忆病人
    2020-11-22 03:14

    I gave up trying to fix this issue.

    My IIS web.config had the relevant "Access-Control-Allow-Methods" in it, I experimented adding config settings to my Angular code, but after burning a few hours trying to get Chrome to call a cross-domain JSON web service, I gave up miserably.

    In the end, I added a dumb ASP.Net handler webpage, got that to call my JSON web service, and return the results. It was up and running in 2 minutes.

    Here's the code I used:

    public class LoadJSONData : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
    
            string URL = "......";
    
            using (var client = new HttpClient())
            {
                // New code:
                client.BaseAddress = new Uri(URL);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Authorization", "Basic AUTHORIZATION_STRING");
    
                HttpResponseMessage response = client.GetAsync(URL).Result;
                if (response.IsSuccessStatusCode)
                {
                    var content = response.Content.ReadAsStringAsync().Result;
                    context.Response.Write("Success: " + content);
                }
                else
                {
                    context.Response.Write(response.StatusCode + " : Message - " + response.ReasonPhrase);
                }
            }
        }
    
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    

    And in my Angular controller...

    $http.get("/Handlers/LoadJSONData.ashx")
       .success(function (data) {
          ....
       });
    

    I'm sure there's a simpler/more generic way of doing this, but life's too short...

    This worked for me, and I can get on with doing normal work now !!

提交回复
热议问题