简体   繁体   English

XMLHttpRequest无法加载没有'Access-Control-Allow-Origin'>头出现在所请求的资源上

[英]XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' > header is present on the requested resource

I have an angular APP with .net CORE web API, where the first request is against a /token service, however I get this error about CORS, but apparently I already have it enabled, what am I missing? 我有一个带有.net CORE Web API的有角度的APP,其中第一个请求是针对/ token服务的,但是我遇到了有关CORS的错误,但是显然我已经启用了它,我还缺少什么?

:8088/#/home:1 XMLHttpRequest cannot load http://example.com:90/api/token . :8088 /#/ home:1 XMLHttpRequest无法加载http://example.com:90/api/token No 'Access-Control-Allow-Origin' header is present on the requested resource. 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 Origin ' http://example.com:8088 ' is therefore not allowed access. 因此,不允许访问来源' http://example.com:8088 '。

     public partial class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();

        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin(); // For anyone access.
            //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
            // Add framework services.
            services.AddMvc()
                    .AddJsonOptions(a => a.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()); ;



            //using Dependency Injection
            services.AddSingleton<IEcommerceRepository, EcommerceRepository>();
            //services.AddSingleton<ITodoTerrenoRepository, TodoTerrenoRepository>();

            services.AddDbContext<EcommerContext>(options =>
             options.UseSqlServer(Configuration.GetConnectionString("AuthentConnection")));
            services.AddDbContext<TODOTERRENOContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


            services.Configure<IISOptions>(options =>
            {

                options.AutomaticAuthentication = true;
                options.ForwardClientCertificate = true;
                options.ForwardWindowsAuthentication = true;


            });


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            ConfigureAuth(app);

            app.UseCors("SiteCorsPolicy");
            app.UseMvc();


        }
    }
}

In my angular APP, i have this: 在我的角度APP中,我有这个:

LoggingService.js LoggingService.js

  angular
        .module('common.services')
        .factory('loginservice', ['$http', 'appSettings', loginservice]);

        function loginservice($http, appSettings) {

            this.login = function () {
                var resp = $http({
                    url: appSettings.serverPath + 'token',
                    method: 'POST',
                    data: $.param({grant_type: 'password', username: appSettings.username, password: appSettings.password }),

                     headers: {
                        'Content-Type': 'application/x-www-form-urlencoded' }
                });
                return resp;
            };
            return { login: this.login }
        }

LoginController.js

app.controller('logincontroller', ['$scope', 'loginservice', 'userProfile', '$rootScope', logincontroller]);

function logincontroller($scope, loginservice, userProfile, $rootScope) {
        $scope.title = 'logincontroller';

        $scope.IniciarLogin = function () {

            var loginResult = loginservice.login();   

            loginResult.then(function (resp) {

                userProfile.setProfile(resp.data.userName, resp.data.access_token, resp.data.refresh_token);
            }, function (response) {

                alert("error");
            });

        }


        $scope.logout = function () {
            sessionStorage.removeItem('accessToken');
            if (sessionStorage.getItem('userSessionName') != null){
                sessionStorage.removeItem('userSessionName');
            }
        }
    }

The web API token authentication was built as shown in the link below, I wont paste their entire code: Web API令牌认证的构建如下面的链接所示,我不会粘贴其完整代码:

https://stormpath.com/blog/token-authentication-asp-net-core https://stormpath.com/blog/token-authentication-asp-net-core

you specify app.UseCors("AllowAllHeader"); 您指定app.UseCors(“ AllowAllHeader”); but your policy name is "AllowAllHeaders" 但您的策略名称是“ AllowAllHeaders”

if you remove that line, your call to app.UseCors("AllowAllOrigins"); 如果删除该行,则对app.UseCors(“ AllowAllOrigins”)的调用; should handle everything (since you specify AllowAnyHeader() in the "AllowAllOrigins" policy 应该处理所有事情(因为您在“ AllowAllOrigins”策略中指定了AllowAnyHeader()

In this part of code, you are trying add the configure cors after put the app variable into ConfigureAuth like parameter. 在这部分代码中,您将app变量放入类似ConfigureAuth的参数后,尝试添加configure cors。 Then, you should configure first the CORS and then pass the variable app into ConfigureAuth. 然后,您应该先配置CORS,然后将变量app传递到ConfigureAuth。

You can see in the code below: 您可以在下面的代码中看到:

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseCors("SiteCorsPolicy");
        app.UseMvc();

        ConfigureAuth(app);           


    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 XMLHttpRequest无法加载。 。 。 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 - XMLHttpRequest cannot load . . . No 'Access-Control-Allow-Origin' header is present on the requested resource. XMLHttpRequest无法加载http:// *********。 请求的资源上不存在“ Access-Control-Allow-Origin”标头 - XMLHttpRequest cannot load http://*********. No 'Access-Control-Allow-Origin' header is present on the requested resource XMLHttpRequest无法加载“…所请求的资源上没有&#39;Access-Control-Allow-Origin&#39;头。” — jQuery - XMLHttpRequest cannot load “ …No 'Access-Control-Allow-Origin' header is present on the requested resource.” — Jquery XMLHttpRequest无法加载…所请求的资源上没有“ Access-Control-Allow-Origin”标头 - XMLHttpRequest cannot load…No 'Access-Control-Allow-Origin' header is present on the requested resource XMLHttpRequest请求的资源上没有“Access-Control-Allow-Origin”标头 - XMLHttpRequest No 'Access-Control-Allow-Origin' header is present on the requested resource XMLHttpRequest无法加载。 请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此不允许原点访问 - XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access XMLHttpRequest无法加载请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin'http:// localhost:3000'Google maps - XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' Google maps XMLHttpRequest无法加载http://example.com/myapp/jsonurl/。 请求的资源上不存在“ Access-Control-Allow-Origin”标头 - XMLHttpRequest cannot load http://example.com/myapp/jsonurl/. No 'Access-Control-Allow-Origin' header is present on the requested resource 仅限Chrome中的错误:XMLHttpRequest无法加载文件网址请求的资源上没有“Access-Control-Allow-Origin”标头 - Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource 完整日历CakePhp 3.x和错误:XMLHttpRequest无法加载“…”。 请求的资源上没有&#39;Access-Control-Allow-Origin&#39;标头吗? - Full Calendar CakePhp 3.x and Error: XMLHttpRequest cannot load '…'. No 'Access-Control-Allow-Origin' header is present on the requested resource?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM