AngularJS performs an OPTIONS HTTP request for a c

2018-12-31 05:19发布

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 XHR request that angular performs must be cross-domain. I've added the appropriate CORS header to my server for the HTTP request to make this work, but it doesn't seem to work. The problem is that when I inspect the HTTP requests in my browser (chrome) the request sent to the asset file is an OPTIONS request (it should be a GET request).

I'm not sure whether this is a bug in AngularJS or if I need to configure something. From what I understand the XHR wrapper can't make an OPTIONS HTTP request so it looks like the browser is trying to figure out if is "allowed" to download the asset first before it performs the GET request. If this is the case, then do I need to set the CORS header (Access-Control-Allow-Origin: http://asset.host...) with the asset host as well?

13条回答
倾城一夜雪
2楼-- · 2018-12-31 05:52

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

查看更多
梦该遗忘
3楼-- · 2018-12-31 05:53

NOTE: Not sure it works with the latest version of Angular.

ORIGINAL:

It's also possible to override the OPTIONS request (was only tested in Chrome):

app.config(['$httpProvider', function ($httpProvider) {
  //Reset headers to avoid OPTIONS request (aka preflight)
  $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
}]);
查看更多
君临天下
4楼-- · 2018-12-31 05:53

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

查看更多
孤独寂梦人
5楼-- · 2018-12-31 05:54

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

查看更多
若你有天会懂
6楼-- · 2018-12-31 05:54

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.

查看更多
泛滥B
7楼-- · 2018-12-31 05:58

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.

查看更多
登录 后发表回答