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

后端 未结 14 1367
生来不讨喜
生来不讨喜 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:09

    Your service must answer an OPTIONS request with headers like these:

    Access-Control-Allow-Origin: [the same origin from the request]
    Access-Control-Allow-Methods: GET, POST, PUT
    Access-Control-Allow-Headers: [the same ACCESS-CONTROL-REQUEST-HEADERS from request]
    

    Here is a good doc: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server

    0 讨论(0)
  • 2020-11-22 03:10

    For Angular 1.2.0rc1+ you need to add a resourceUrlWhitelist.

    1.2: release version they added a escapeForRegexp function so you no longer have to escape the strings. You can just add the url directly

    'http://sub*.assets.example.com/**' 
    

    make sure to add ** for sub folders. Here is a working jsbin for 1.2: http://jsbin.com/olavok/145/edit


    1.2.0rc: If you are still on a rc version, the Angular 1.2.0rc1 the solution looks like:

    .config(['$sceDelegateProvider', function($sceDelegateProvider) {
         $sceDelegateProvider.resourceUrlWhitelist(['self', /^https?:\/\/(cdn\.)?yourdomain.com/]);
     }])
    

    Here is a jsbin example where it works for 1.2.0rc1: http://jsbin.com/olavok/144/edit


    Pre 1.2: For older versions (ref http://better-inter.net/enabling-cors-in-angular-js/) you need to add the following 2 lines to your config:

    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    

    Here is a jsbin example where it works for pre 1.2 versions: http://jsbin.com/olavok/11/edit

    0 讨论(0)
  • 2020-11-22 03:10

    Somehow I fixed it by changing

    <add name="Access-Control-Allow-Headers" 
         value="Origin, X-Requested-With, Content-Type, Accept, Authorization" 
         />
    

    to

    <add name="Access-Control-Allow-Headers" 
         value="Origin, Content-Type, Accept, Authorization" 
         />
    
    0 讨论(0)
  • 2020-11-22 03:12

    Here is the way I fixed this issue on ASP.NET

    • First, you should add the nuget package Microsoft.AspNet.WebApi.Cors

    • Then modify the file App_Start\WebApiConfig.cs

      public static class WebApiConfig    
      {
         public static void Register(HttpConfiguration config)
         {
            config.EnableCors();
      
            ...
         }    
      }
      
    • Add this attribute on your controller class

      [EnableCors(origins: "*", headers: "*", methods: "*")]
      public class MyController : ApiController
      {  
          [AcceptVerbs("POST")]
          public IHttpActionResult Post([FromBody]YourDataType data)
          {
               ...
               return Ok(result);
          }
      }
      
    • I was able to send json to the action by this way

      $http({
              method: 'POST',
              data: JSON.stringify(data),
              url: 'actionurl',
              headers: {
                  'Content-Type': 'application/json; charset=UTF-8'
              }
          }).then(...)
      

    Reference : Enabling Cross-Origin Requests in ASP.NET Web API 2

    0 讨论(0)
  • 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 !!

    0 讨论(0)
  • 2020-11-22 03:20

    This fixed my problem:

    $http.defaults.headers.post["Content-Type"] = "text/plain";
    
    0 讨论(0)
提交回复
热议问题