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

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

    Perfectly described in pkozlowski's comment. I had working solution with AngularJS 1.2.6 and ASP.NET Web Api but when I had upgraded AngularJS to 1.3.3 then requests failed.

    • Solution for Web Api server was to add handling of the OPTIONS requests at the beginning of configuration method (more info in this blog post):

      app.Use(async (context, next) =>
      {
          IOwinRequest req = context.Request;
          IOwinResponse res = context.Response;
          if (req.Path.StartsWithSegments(new PathString("/Token")))
          {
              var origin = req.Headers.Get("Origin");
              if (!string.IsNullOrEmpty(origin))
              {
                  res.Headers.Set("Access-Control-Allow-Origin", origin);
              }
              if (req.Method == "OPTIONS")
              {
                  res.StatusCode = 200;
                  res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST");
                  res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization", "content-type");
                  return;
              }
          }
          await next();
      });
      

提交回复
热议问题