GVKun编程网logo

angularjs – Keycloak angular No存在“Access-Control-Allow-Origin”标题(angularjs提示框)

14

本篇文章给大家谈谈angularjs–KeycloakangularNo存在“Access-Control-Allow-Origin”标题,以及angularjs提示框的知识点,同时本文还将给你拓展A

本篇文章给大家谈谈angularjs – Keycloak angular No存在“Access-Control-Allow-Origin”标题,以及angularjs提示框的知识点,同时本文还将给你拓展Access-Control-Allow-Origin angularjs到php、angular js nginx cors – 没有“Access-Control-Allow-Origin”标题、Angular11 Web 应用程序被 CORS 策略阻止:在预检响应中 Access-Control-Allow-Headers 不允许 access-control-allow-origin、Angularjs / sailsjs:Access-Control-Allow-Headers不允许使用Access-Control-Allow-Origin等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

angularjs – Keycloak angular No存在“Access-Control-Allow-Origin”标题(angularjs提示框)

angularjs – Keycloak angular No存在“Access-Control-Allow-Origin”标题(angularjs提示框)

我已经将keycloak与角度应用程序集成在一起.基本上,前端和后端都在不同的服务器上.Backend应用程序在apache tomcat 8上运行.前端应用程序正在JBoss欢迎内容文件夹上运行.

Angular配置

angular.element(document).ready(function ($http) {
    var keycloakAuth = new Keycloak('keycloak.json');
    auth.loggedIn = false;
    keycloakAuth.init({ onLoad: 'login-required' }).success(function () {
        keycloakAuth.loadUserInfo().success(function (userInfo) {
            console.log(userInfo);  
        });
        auth.loggedIn = true;
        auth.authz = keycloakAuth;
        auth.logoutUrl = keycloakAuth.authServerUrl + "/realms/app1/protocol/openid-connect/logout?redirect_uri=http://35.154.214.8/hrms-keycloak/index.html";
        module.factory('Auth',function() {
            return auth;
        });
        angular.bootstrap(document,["themesApp"]);
    }).error(function () {
            window.location.reload();
        });

});
module.factory('authInterceptor',function($q,Auth) {
    return {
        request: function (config) {
            var deferred = $q.defer();
            if (Auth.authz.token) {
                Auth.authz.updatetoken(5).success(function() {
                    config.headers = config.headers || {};
                    config.headers.Authorization = 'Bearer ' + Auth.authz.token;
                    deferred.resolve(config);
                }).error(function() {
                        deferred.reject('Failed to refresh token');
                    });
            }
            return deferred.promise;
        }
    };
});
module.config(["$httpProvider",function ($httpProvider)  {
    $httpProvider.interceptors.push('authInterceptor');
}]);

请求标题

Accept:*/*
Accept-Encoding:gzip,deflate
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:35.154.214.8:8080
Origin:http://35.154.214.8
Referer:http://35.154.214.8/accounts-keycloak/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/59.0.3071.115 Safari/537.36

Web控制台出错.

XMLHttpRequest cannot load http://35.154.214.8:8080/company/loadCurrencyList. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://35.154.214.8' is therefore not allowed access.

Cors过滤后端

@Component
public class CORSFilter implements Filter {
    static Logger logger = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws servletexception {
    }

    @Override
    public void doFilter(ServletRequest request,ServletResponse res,FilterChain chain) throws IOException,servletexception {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","*");
        response.setHeader("Access-Control-Max-Age","3600");
        response.setHeader("Access-Control-Allow-Headers","*");
        chain.doFilter(request,response);
    }

    public void destroy() {
    }
}

解决方法

我和KeyCloak以及CORS一起战斗了大约两个星期,这是我的解决方案(对于keycloak 3.2.1):

这一切都与配置KeyCloak服务器有关.
似乎是,你的王国的WebOrigin需要

*

只有一个来源“*”.

多数民众赞成,我需要的是什么.

如果您将服务器作为WebOrigin输入,则问题就出现了.
当您在JavaScript中调用keycloak.init时,keycloak不会生成CORS头,因此您必须手动配置它们,并且一旦这样做,并在成功初始化后调用keycloak.getUserInfo – 您将获得双CORS头,这不是允许.

在keycloak邮件列表的深处,你需要在keycloak.json中设置enable-cors = true,但是在keycloak.gitbooks.io上没有任何关于它的内容.所以似乎不是真的.

在描述JavaScript和Node.Js适配器时,他们也没有提到CORS,我不知道为什么,似乎根本不重要.

它似乎也是,您不应该触摸WildFly配置来提供CORS标头.

此外,OIDC中的CORS是一个特殊的KeyCloak功能(而不是bug).

希望这个答案对你有好处.

Access-Control-Allow-Origin angularjs到php

Access-Control-Allow-Origin angularjs到php

我的场景由两个webserver组成,一个是本地的,一个是远程的.

本地Web服务器(Apache)处理一个Web应用程序,我想在其中向远程Web服务器(Lighttpd)发出ajax请求.

Ajax请求使用angularjs $http.

var req = {
    method: 'POST',url: 'http://url/myPHP.PHP',headers: {
        'Authorization': 'Basic ' + btoa('username:password'),'Content-Type': 'application/x-www-form-urlencoded'
    },xhrFields: {
       withCredentials: true
    },crossDomain: true,data: xmlString
}

$http(req).then(function () {
    console.log("OK!");
});

远程PHP脚本是:

<?PHP
    echo "You have CORS!";
?>

不幸的是我有一个

401 Unhauthorized
XMLHttpRequest cannot load http://url/myPHP.PHP. Response to    preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access. The response had HTTP status code 401.

远程Web服务器具有.htpasswd身份验证模式启用和配置的CORS请求.

关注一个lighttpd.conf

setenv.add-response-header = ( "Access-Control-Allow-Origin" => "*" )

解决方法

要使add-response-header在lighttpd中工作,必须在server.modules中启用mod_setenv.但是,您必须在mod_status之前启用此mod_setenv.

server.modules = (
    # ...
    "mod_fastcgi","mod_rewrite","mod_redirect","mod_setenv",## before mod_status
    "mod_status",# ...
)

或者,您可以使用PHP输出cors标头

<?PHP
header("Access-Control-Allow-Origin: *");
?>

我还想补充一点,如果您要发送http basic / digest auth数据,则不能使用通配符作为原点.您必须使用实际的源域

setenv.add-response-header = ( "Access-Control-Allow-Origin" => "example.com" )
setenv.add-response-header = ( "Access-Control-Allow-Credentials" => "true" )

angular js nginx cors – 没有“Access-Control-Allow-Origin”标题

angular js nginx cors – 没有“Access-Control-Allow-Origin”标题

我知道这个问题的不同版本已经被问到,我已经阅读了所有关于SO和Google的相关问题和答案。

我正在尝试从angularJS应用程序向Nginx服务器发出跨域请求。 所有的GET请求行为正常,但我的POST请求不。

Chrome给了我一个“访问控制允许来源”错误,所以我添加了以下内容到我的Nginx服务器configuration:

location / { if ($http_origin ~* (https?://.*.mysite.com(:[0-9]+)?)) { set $cors "true"; } if ($request_method = ''OPTIONS'') { set $cors "${cors}options"; } # non-OPTIONS indicates a normal CORS request if ($request_method = ''GET'') { set $cors "${cors}get"; } if ($request_method = ''POST'') { set $cors "${cors}post"; } # if it''s a GET or POST,set the standard CORS responses header if ($cors = "trueget") { add_header ''Access-Control-Allow-Origin'' "$http_origin"; #add_header ''Access-Control-Allow-Credentials'' ''true''; } if ($cors = "truepost") { add_header ''Access-Control-Allow-Origin'' "$http_origin"; #add_header ''Access-Control-Allow-Credentials'' ''true''; } if ($cors = "trueoptions") { add_header ''Access-Control-Allow-Origin'' "$http_origin"; #add_header ''Access-Control-Allow-Credentials'' ''true''; # # Return special preflight info # add_header ''Access-Control-Max-Age'' 1728000; add_header ''Access-Control-Allow-Methods'' ''GET,POST,OPTIONS''; add_header ''Access-Control-Allow-Headers'' ''Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since''; add_header ''Content-Length'' 0; add_header ''Content-Type'' ''text/plain charset=UTF-8''; return 204; } }

OPTIONS请求返回状态204和添加的标题预期:

POST请求不允许 – 405不允许 – Nginx,即使包含头文件

在Apache中使用Access-Control-Allow-Origin标头处理多个域

绕过“选项请求”的authentication(所有的头都在响应中发送)

从浏览器上传文件到另一个域的最好方法是什么?

飞行前OPTIONS请求故障转移HTTPS

Request URL:<code>http://otherSite/shfofx/PHP/Add/addTrade</code> Request Method:OPTIONS Status Code:204 No Content Request Headers Accept:*/* Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 Access-Control-Request-Headers:accept,x-requested-with,content-type Access-Control-Request-Method:POST AlexaToolbar-ALX_NS_PH:AlexaToolbar/alxg-3.2 Cache-Control:no-cache Connection:keep-alive Host:otherSite Origin:<code>http://test-shf.mysite.com</code> Pragma:no-cache Referer:<code>http://test-shf.mysite.com/portfolio</code> User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/31.0.1650.63 Safari/537.36 Response Headersview source Access-Control-Allow-Headers:Authorization,User- Agent,If-Modified-Since Access-Control-Allow-Methods:GET,OPTIONS Access-Control-Allow-Origin:<code>http://test-shf.mysite.com</code> Access-Control-Max-Age:1728000 Connection:keep-alive Content-Length:0 Content-Type:text/plain charset=UTF-8 Date:Thu,02 Jan 2014 22:54:58 GMT Server:Nginx/1.2.6 (Ubuntu)

然后,我在Chromenetworking标签中看到一个包含POST请求的networking调用,该请求被以下控制台输出取消:

XMLHttpRequest cannot load <code>http://otherSite/shfofx/PHP/Add/addTrade</code>. No ''Access-Control-Allow-Origin'' header is present on the requested resource. Origin ''http://test-shf.mysite.com'' is therefore not allowed access.

取消的POST请求的标题信息是:

Request URL:<code>http://otherSite/shfofx/PHP/Add/addTrade</code> Request Headers Accept:application/json,text/plain,*/* Cache-Control:no-cache Content-Type:application/json;charset=UTF-8 Origin:<code>http://test-shf.mysite.com</code> Pragma:no-cache Referer:<code>http://test-shf.mysite.com/portfolio</code> User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/31.0.1650.63 Safari/537.36 X-Requested-With:XMLHttpRequest Request Payload {UserFIID:0,FinancialInstID:4,FinancialInstName:undefined,UserID:1,SHFUserID:1,…}

为什么允许预检OPTIONS请求,但我的POST请求被取消?

Nginx和CORS问题

在Windows 8上启用CORS

apache mod_proxy,为跨域Ajax调用configurationProxyPass&ProxyPassReverse

设置Nginx允许跨域请求子域

如何configurationWAMP apache服务器以允许跨域请求ajax?

所以答案简单而烦人。

我的开发者服务器被配置为允许松散解释的文件名,所以:

Request URL:http://otherSite/shfofx/PHP/Add/addTrade

将解决addTrade.PHP,代码将按预期执行。 但是,在我的测试服务器中,服务器被配置为仅返回请求的确切区分大小写的页面。 所以,POST请求返回了''404 Not Found''的状态。

更糟糕的是,Chrome的网络选项卡没有中继404响应,只是“访问控制 – 允许 – 来源”错误。 直到我检查了服务器响应的Firefox,我才能够确定并解决问题。

我只是改变了:

Request URL:http://otherSite/shfofx/PHP/Add/addTrade

至:

Request URL:http://otherSite/shfofx/PHP/Add/addTrade.PHP

就是这样。

总结

以上是小编为你收集整理的angular js nginx cors – 没有“Access-Control-Allow-Origin”标题全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

Angular11 Web 应用程序被 CORS 策略阻止:在预检响应中 Access-Control-Allow-Headers 不允许 access-control-allow-origin

Angular11 Web 应用程序被 CORS 策略阻止:在预检响应中 Access-Control-Allow-Headers 不允许 access-control-allow-origin

如何解决Angular11 Web 应用程序被 CORS 策略阻止:在预检响应中 Access-Control-Allow-Headers 不允许 access-control-allow-origin?

我正在尝试使用带有 angular 11 的 reddit api 在本地开发一个网络应用程序,我正在尝试使用以下链接中的说明获取身份验证令牌:Reddit OAuth2 docs

但是,我遇到了一些问题。

我已经设置了我的标头以包含服务中的常用方法,例如:

httpOptions = {
headers: new HttpHeaders({
  "Content-Type": "application/x-www-form-urlencoded","Access-Control-Allow-Origin": "*","Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT","Access-Control-Allow-Headers": "Origin,X-Requested-With,Content-Type,Accept,x-client-key,x-client-token,x-client-secret,Authorization",})

};

我设置了在服务中检索身份验证令牌的函数:

getRedditAuthToken() {
 console.log("Auth token");
 return this.http.get<any>(this.redditAuthUrl,this.httpOptions);
}

redditAuthUrl 的设置参数取自 reddit 的 oAuth 文档:

https://www.reddit.com/api/v1/authorize?client_id=CLIENT_ID&response_type=TYPE&
state=RANDOM_STRING&redirect_uri=URI&duration=DURATION&scope=ScopE_STRING

最后,服务正在被组件检索:

getRedditAuthToken(): void {
    this.redditService.getRedditAuthToken().subscribe((data) => {
      console.log(data);
    });
  }

虽然在尝试访问身份验证令牌(在网络检查器上找到)时出现以下错误:

Access to XMLHttpRequest at ''https://www.reddit.com/api/v1/authorize.compact?client_id=<client_id>&response_type=code&state=<random_string>&redirect_uri=http://localhost:4200/reddit&duration=temporary&scope=identity'' from origin ''http://localhost:4200'' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
GET https://www.reddit.com/api/v1/authorize.compact?client_id=<client_id>&response_type=code&state=<random_string>&redirect_uri=http://localhost:4200/reddit&duration=temporary&scope=identity net::ERR_Failed
ERROR HttpErrorResponse {headers: HttpHeaders,status: 0,statusText: "UnkNown Error",url: "https://www.reddit.com/api/v1/authorize.compact?cl…ost:4200/reddit&duration=temporary&scope=identity",ok: false, …}

我曾多次尝试解决方案,例如使用代理 json 文件启动 angular、修改 httpHeaders、测试其他 reddit oAuth 令牌检索(使用 post 方法),但我总是遇到相同的 CORS 问题。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Angularjs / sailsjs:Access-Control-Allow-Headers不允许使用Access-Control-Allow-Origin

Angularjs / sailsjs:Access-Control-Allow-Headers不允许使用Access-Control-Allow-Origin

我在角度js和sails.js(node.js框架)之间的角色问题上苦苦挣扎

我尝试修复错误:XMLHttpRequest无法加载http://localhost:1337/en/auth/forgetpass/email.请求标头字段Access-Control-Allow-Origin不允许Access-Control-Allow-Origin.

当我不激活我的拦截器时它运作良好.我没有这个错误.当我激活它时,我有错误.

在我的.config中,我设置了以下代码:

//Enable cross domain calls
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

$httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = '*';
$httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
$httpProvider.defaults.headers.common['Access-Control-Allow-Methods'] = 'GET,POST,PUT,HEAD,DELETE,OPTIONS';

$httpProvider.interceptors.push('TokenInterceptor');

然后在我的拦截器中我设置下面的代码:

return {
    request: function (config) {
      var id = Session.getprop('id');
      if(id) {
        config.headers = config.headers || {};
        config.headers.Authorization = 'Bearer ' + id;
      }
        return config;
    },...

最后,chrome网络标签的结果是:

Remote Address:127.0.0.1:1337
Request URL:http://localhost:1337/en/auth/forgetpass/email
Request Method:OPTIONS
Status Code:200 OK

Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:*
Access-Control-Allow-Methods:GET,OPTIONS,HEAD
Access-Control-Allow-Origin:*
Allow:GET,TRACE,copY,LOCK,MKCOL,MOVE,PROPFIND,PROPPATCH,UNLOCK,REPORT,MKACTIVITY,CHECKOUT,MERGE,M-SEARCH,NOTIFY,SUBSCRIBE,UNSUBSCRIBE,PATCH
Connection:keep-alive
Content-Length:154
Content-Type:text/html; charset=utf-8
Date:Sun,12 Apr 2015 23:51:14 GMT
Set-Cookie:sails.sid=s%3A-bZxQgFntbDqTtaFyWDFFgFr.szR0F68VfIBjVW9kyans9d6v5fz7RMtalQCoMfdbH%2Fg; Path=/;   HttpOnly
X-Powered-By:Sails <sailsjs.org>

Request Headers
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:access-control-allow-origin,accept,access-control-allow-headers,access-control-allow-methods
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:1337
Origin:http://localhost:9000
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/41.0.2272.118 Safari/537.36

我仍然得到同样的错误.一个主意?

非常感谢!

好的,我终于找到了这个问题.

我将响应和请求标头与拦截器及其进行了比较.

我改变我的代码如下,它的工作原理.

在angularjs的app.js中

我评论了所有标题部分.

//Enable cross domain calls
  /*  $httpProvider.defaults.useXDomain = true;

//Remove the header used to identify ajax call  that would prevent CORS from working
delete $httpProvider.defaults.headers.common['X-Requested-With'];

$httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = 'origin,content-type,accept';
$httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
$httpProvider.defaults.headers.common['Access-Control-Allow-Methods'] = 'GET,OPTIONS';*/

$httpProvider.interceptors.push('TokenInterceptor');

在我的sails.js cors setup config中我评论了方法和标题.它运作良好.

module.exports.cors = {

  /***************************************************************************
  *                                                                          *
  * Allow CORS on all routes by default? If not,you must enable CORS on a   *
  * per-route basis by either adding a "cors" configuration object to the    *
  * route config,or setting "cors:true" in the route config to use the      *
  * default settings below.                                                  *
  *                                                                          *
  ***************************************************************************/

   allRoutes: true,/***************************************************************************
  *                                                                          *
  * Which domains which are allowed CORS access? This can be a               *
  * comma-delimited list of hosts (beginning with http:// or https://) or    *
  * "*" to allow all domains CORS access.                                    *
  *                                                                          *
  ***************************************************************************/

   origin: '*',/***************************************************************************
  *                                                                          *
  * Allow cookies to be shared for CORS requests?                            *
  *                                                                          *
  ***************************************************************************/

   credentials: true

  /***************************************************************************
  *                                                                          *
  * Which methods should be allowed for CORS requests? This is only used in  *
  * response to preflight requests (see article linked above for more info)  *
  *                                                                          *
  ***************************************************************************/

  // methods: 'GET,HEAD',/***************************************************************************
  *                                                                          *
  * Which headers should be allowed for CORS requests? This is only used in  *
  * response to preflight requests.                                          *
  *                                                                          *
  ***************************************************************************/

  // headers: 'origin,accept'

};

今天关于angularjs – Keycloak angular No存在“Access-Control-Allow-Origin”标题angularjs提示框的分享就到这里,希望大家有所收获,若想了解更多关于Access-Control-Allow-Origin angularjs到php、angular js nginx cors – 没有“Access-Control-Allow-Origin”标题、Angular11 Web 应用程序被 CORS 策略阻止:在预检响应中 Access-Control-Allow-Headers 不允许 access-control-allow-origin、Angularjs / sailsjs:Access-Control-Allow-Headers不允许使用Access-Control-Allow-Origin等相关知识,可以在本站进行查询。

本文标签: