AngularJS 禁用 CORS? [英] AngularJS disabling CORS?

查看:22
本文介绍了AngularJS 禁用 CORS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我完全遗漏了一些东西,但我有一个在本地运行的服务器,并且没有将 Angular 配置为对 $http 请求使用 CORS.当我向 localhost: 发出 HTTP 请求时,我看到 Chrome 首先创建了一个 OPTIONS 请求.

Maybe I'm missing something entirely, but I have a server running locally, and have not configured Angular to use CORS for $http requests. When I make an HTTP request to localhost:<port>, I see Chrome create an OPTIONS request first.

因为我需要支持 IE 8 - 而 AngularJS 肯定不会在那里使用 CORS - 我需要删除 CORS.

Because I need to support IE 8 - and AngularJS definitely will not work there with CORS - I need to remove CORS.

我尝试使用 $http.post 包装器直接设置 POST 方法 not ,但无济于事.也许这与 https://github.com/angular/angular.js/issues/有关1585

I have tried directly setting the POST method not using the $http.post wrapper with no avail. Perhaps this is related to https://github.com/angular/angular.js/issues/1585

我还尝试直接从控制器调用 jQuery ajax 帖子 - 即使 CORS 选项为 false(因为它似乎默认为 true).它仍然会创建 CORS 请求.

I've also tried calling a jQuery ajax post directly from a controller - even with the CORS option as false (because it seemed to default to true). It still creates a CORS request.

这是什么配置?

推荐答案

CORS 是您请求 url 的结果,不是您可以设置的任何配置.如果您的来源与请求 url 协议/域/端口不匹配,您将收到 CORS 请求——没有例外.

CORS is a result of your request url, not of any configuration you can set. If your origin does not match the request url protocol/domain/port, you will get a CORS request--no exceptions.

例如,来源为 http://www.example.com:8080 :

这是一个 CORS 请求:http://example.com:8080/path.json(不同的子域)

This is a CORS request: http://example.com:8080/path.json (different subdomain)

这是一个 CORS 请求:http://www.example.com/path.json(不同的端口)

This is a CORS request: http://www.example.com/path.json (different port)

这是一个 CORS 请求:https://www.example.com:8080/path.json(不同的协议)

This is a CORS request: https://www.example.com:8080/path.json (different protocol)

不是 CORS 请求:http://www.example.com:8080/path.json(协议、域和端口都与源匹配)

This is NOT a CORS request: http://www.example.com:8080/path.json (the protocol, domain, and port all match the origin)

话虽如此,发生 OPTIONS 请求是因为您有标准标头之外的标头(很可能,您的请求具有 X-Requested-With 标头).在 Angular.js 中,您可以使用以下命令删除它:

That being said, the OPTIONS request is happening because you have a header outside of the standard headers (very likely, your request has an X-Requested-With header). In Angular.js, you can remove this with:

angular.module('yourModuleHere')
    .config(function ($httpProvider) {
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    });

请注意,对于 Angular.js 1.2 及更高版本,X-Requested-With 不在默认的通用标头列表中.您无需将其从列表中删除.

Note that for Angular.js 1.2 and above, X-Requested-With is not in the default common headers list. You don't need to remove it from the list.

这篇关于AngularJS 禁用 CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆