gpt4 book ai didi

javascript - XMLHttpRequest 无法加载 No 'Access-Control-Allow-Origin' > 请求的资源上存在 header

转载 作者:行者123 更新时间:2023-12-01 03:50:51 28 4
gpt4 key购买 nike

我有一个带有 .net CORE Web API 的 Angular 应用程序,其中第一个请求是针对/token 服务的,但是我收到了有关 CORS 的错误,但显然我已经启用了它,我缺少什么?

:8088/#/home:1 XMLHttpRequest cannot load http://example.com:90/api/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com:8088' is therefore not allowed access.

     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();


}
}
}

在我的 Angular 应用程序中,我有这个:

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');
}
}
}

Web API token 身份验证的构建如下面的链接所示,我不会粘贴其完整代码:

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

最佳答案

在这部分代码中,您尝试在将应用程序变量放入类似ConfigureAuth的参数后添加配置cors。然后,您应该首先配置 CORS,然后将变量 app 传递到ConfigureAuth。

您可以在下面的代码中看到:

  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);


}

关于javascript - XMLHttpRequest 无法加载 No 'Access-Control-Allow-Origin' > 请求的资源上存在 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43218075/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com