当前位置: 首页 > 知识库问答 >
问题:

无法进行跨源请求(CORS)

谷隐水
2023-03-14

我已经在我的ASP中启用了CORS。NET MVC API,使用以下代码:

        public static void Configure(IApplicationBuilder app)
        {
            app.UseCors("CorsName");
        }
        public static void ConfigureServices(IServiceCollection services, IConfiguration config)
        {
            // Configuration and adding Cross-origin resource sharing
            services.AddCors(options =>
            {
                options.DefaultPolicyName = "CorsName";
                options.AddPolicy("CorsName", builder =>
                {
                    builder
                        .WithOrigins(config["AppSettings:CorsOrigin"])
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
                        .AllowAnyOrigin()
                        .Build();
                });
            });
        }

我尝试从API获取数据,打开localhost:6320/API/users,它工作了,我获取了所有数据。现在,当我尝试从Angular 7应用程序获取数据时,数据未加载,出现错误

“访问位于的XMLHttpRequest”http://localhost:6320/api/users“起源”http://localhost:4200'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在'access control Allow Origin'标头。"

如果启用了CORS,为什么尝试从Angular应用程序获取数据时出错?

这里是应用设置

  "AppSettings": {
    "DashboardUrl": "http://127.0.0.1:4200",
    "CorsOrigin": "http://localhost:4200"
  }

从启动到启动配置。反恐精英

        public Startup(IHostingEnvironment env, IConfiguration configuration)
        {
            Configuration = configuration;

            HostingEnvironment = env;
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment hEnv)
        {
            InitializeIdentityDbAsync(app.ApplicationServices).Wait();
            DiagnosticsStartup.Configure(app, hEnv);
            CorsStartup.Configure(app);
            IdentityStartup.Configure(app, Configuration);
            MVCStartup.Configure(app);
        }
                public void ConfigureServices(IServiceCollection services)
        {
        CorsStartup.ConfigureServices(services, Configuration);
        services.AddAutoMapper();
        services.AddSingleton<IConfiguration>(o => Configuration);
        services.AddScoped<IAppContext, AppContext>();
        services.AddSingleton<IEmailService, EmailService>();
            services.AddScoped<AuthService>();
            services.AddScoped<UserService>();
            EFStartup.ConfigureServices(services, Configuration);
            IdentityStartup.ConfigureServices(services, HostingEnvironment, Configuration);
            MVCStartup.ConfigureServices(services);
            AutoMapperConfig.RegisterMappings(services.BuildServiceProvider());
        }

共有3个答案

巫马瀚漠
2023-03-14

您还必须在前端启用CORS。以下是如何启用角CORS的多种方法之一。

步骤1:在主项目文件夹中创建proxyconfig.json文件(在src和node_modules旁边)。

步骤2:

{
  "/api": {
  "target":"url to the server", (eg: "http://45.33.74.207:3000")
  "secure": false,
  "changeOrigin": true
  }
}

将其保存在proxyconfig中。json文件。

步骤3:添加--代理配置proxyconfig。脚本对象内部启动中的json

"start": "ng serve --proxy-config  proxyconfig.json"

在package.json文件里。

步骤4:用npm start保存并启动项目

注意:如果您以(ng serve)开始项目,它将不起作用。

班泽语
2023-03-14

从startup类中删除此选项:

services.AddCors(options =>
{
    options.AddPolicy("CorsName", builder =>
    {
        builder
            .WithOrigins(config["AppSettings:CorsOrigin"])
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials();
    });
});

在配置方法中,请尝试以下操作:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...
    app.UseCors(builder => {
        builder
        .WithOrigins(config["AppSettings:CorsOrigin"])
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials();
     });
    app.UseMvc();
}

If以这种方式工作,因此您对策略及其对UseCors方法的分配有问题。

简学文
2023-03-14

你加了两次起源。首先,通过。与起源(配置["AppSet: CorsOrigin"]),然后通过。AllowAnyOrigin().如果只允许特定的原点(考虑到您的配置,我认为这是正确的),请删除。AllowAnyOrigin()调用。

尝试:

services.AddCors(options =>
{
    options.AddPolicy("CorsName", builder =>
    {
        builder
            .WithOrigins(config["AppSettings:CorsOrigin"])
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials();
    });
});

检查您从配置["AppSet: CorsOrigin"]中获得的内容。您是否有一个名为AppSet的密钥?

此外,您可能(而且很可能是)正在调用应用程序。UseMvc() 在<代码>应用程序之前。UseCors() 。确保Configure方法的顺序如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...
    app.UseCors("CorsName");
    app.UseMvc();
}

 类似资料:
  • 我正在工作的角度前端项目和使用angular7项目。我使用aws api作为后端。每当我调用aws api时,它都会给我带来以下错误。 跨源请求被阻止:同一源策略不允许读取https://xxxxxxx.execute-api.us-east-1.amazonaws.com/xxx/subscriptionPayment上的远程资源。(原因:在CORS飞行前信道的CORS标头'Access-Con

  • 如果我们向另一个网站发送 fetch 请求,则该请求可能会失败。 例如,让我们尝试向 http://example.com 发送 fetch 请求: try { await fetch('http://example.com'); } catch(err) { alert(err); // fetch 失败 } 正如所料,获取失败。 这里的核心概念是 源(origin)—— 域(domai

  • 当我使用axios发送XMLHttpRequest时,就会发生这种情况。 错误:XMLHttpRequest无法加载https://nuxt-auth-routes.glitch.me/api/login。对飞行前请求的响应没有通过访问控制检查:在所请求的资源上没有“访问-控制-允许-起源”标头。因此,不允许访问源'http://localhost:3000'。

  • 我得到以下错误: 我知道这个问题以前已经回答过了,但我仍然没有找到解决问题的方法。我试着在chrome上运行<code>。exe--允许从命令提示符下的文件访问文件,并将文件移动到本地文件系统,但我仍然收到相同的错误。 我感谢任何建议!

  • 问题内容: 我想用以下代码用jquery ajax解析JSON数组数据: 我的JSON数据是: 但是我没有任何输出…任何人请帮忙… 问题答案: 概念解释 您是否正在尝试进行跨域AJAX调用?意思是,您的服务不在同一Web应用程序路径中托管吗?您的Web服务必须支持方法注入才能执行JSONP。 您的代码看起来不错,并且如果您的Web服务和Web应用程序托管在同一域中,则该代码应该可以正常工作。 当您

  • 问题内容: 我正在尝试将AngularJS设置为与跨域资源进行通信,在该域中,提供我的模板文件的资产宿主位于不同的域上,因此angular执行的XHR请求必须是跨域的。我已将适当的CORS标头添加到服务器上,以进行HTTP请求以使其正常工作,但它似乎不起作用。问题是,当我在浏览器(chrome)中检查HTTP请求时,发送到资产文件的请求是OPTIONS请求(应该是GET请求)。 我不确定这是否是A