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

后端 未结 14 1370
生来不讨喜
生来不讨喜 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();
      });
      
    0 讨论(0)
  • 2020-11-22 03:23

    Little late to the party,

    If you are using Angular 7 (or 5/6/7) and PHP as the API and still getting this error, try adding following header options to the end point (PHP API).

     header("Access-Control-Allow-Origin: *");
     header("Access-Control-Allow-Methods: PUT, GET, POST, PUT, OPTIONS, DELETE, PATCH");
     header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
    

    Note : What only requires is Access-Control-Allow-Methods. But, I am pasting here other two Access-Control-Allow-Origin and Access-Control-Allow-Headers, simply because you will need all of these to be properly set in order Angular App to properly talk to your API.

    Hope this helps someone.

    Cheers.

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

    If you are using Jersey for REST API's you can do as below

    You don't have to change your webservices implementation.

    I will explain for Jersey 2.x

    1) First add a ResponseFilter as shown below

    import java.io.IOException;
    
    import javax.ws.rs.container.ContainerRequestContext;
    import javax.ws.rs.container.ContainerResponseContext;
    import javax.ws.rs.container.ContainerResponseFilter;
    
    public class CorsResponseFilter implements ContainerResponseFilter {
    
    @Override
    public void filter(ContainerRequestContext requestContext,   ContainerResponseContext responseContext)
        throws IOException {
            responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
            responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
    
      }
    }
    

    2) then in the web.xml , in the jersey servlet declaration add the below

        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>YOUR PACKAGE.CorsResponseFilter</param-value>
        </init-param>
    
    0 讨论(0)
  • 2020-11-22 03:25

    The same document says

    Unlike simple requests (discussed above), "preflighted" requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if:

    It uses methods other than GET or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.

    It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

    When the original request is Get with no custom headers, the browser should not make Options request which it does now. The problem is it generates a header X-Requested-With which forces the Options request. See https://github.com/angular/angular.js/pull/1454 on how to remove this header

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

    If you are using a nodeJS server, you can use this library, it worked fine for me https://github.com/expressjs/cors

    var express = require('express')
      , cors = require('cors')
      , app = express();
    
    app.use(cors());
    

    and after you can do an npm update.

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

    For an IIS MVC 5 / Angular CLI ( Yes, I am well aware your problem is with Angular JS ) project with API I did the following:

    web.config under <system.webServer> node

        <staticContent>
          <remove fileExtension=".woff2" />
          <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
        </staticContent>
        <httpProtocol>
          <customHeaders>
            <clear />
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type, atv2" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
          </customHeaders>
        </httpProtocol>
    

    global.asax.cs

    protected void Application_BeginRequest() {
      if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OrdinalIgnoreCase) && Request.HttpMethod == "OPTIONS") {
        Response.Flush();
        Response.End();
      }
    }
    

    That should fix your issues for both MVC and WebAPI without having to do all the other run around. I then created an HttpInterceptor in the Angular CLI project that automatically added in the the relevant header information. Hope this helps someone out in a similar situation.

    0 讨论(0)
提交回复
热议问题