Angular或Angular中的跨源资源共享(CORS)6。在localhost上使用不同端口进行跨域调用时出现问题

问题描述 投票:2回答:3

我遇到过一种情况,我从我的角度6应用程序调用我的弹簧启动应用程序。当我以角度调用HTTP post方法到在不同端口上运行的应用程序时,它会抛出异常。

从'http://localhost:8080/api'访问'http://localhost:4200'的XMLHttpRequest已被CORS策略阻止:对预检请求的响应未通过访问控制检查:它没有HTTP ok状态。

我的Angular应用程序运行'http://localhost:4200'端口号:4200运行'http://localhost:8080/api'的My Spring Boot应用程序:端口号:8080。

没有直接的答案来解决这个问题。很少有黑客可以禁用Chrome中的安全性,使用NGINX可以解决此问题。

angular spring-boot cors cross-domain angular6
3个回答
3
投票

解决上述问题

  1. 首先,您需要为端口4200共享Spring引导资源。使用要共享的资源的@CrossOrigin(originins =“http://localhost:4200”)注释类或方法。
  2. 哟必须在角度应用程序中配置代理。因此,在角度根应用程序中创建proxy.json文件。内容如下 { "/api/*": { "target": "http://localhost:8080", "secure": "false", "logLevel": "debug", "changeOrigin": true } }
  3. 然后运行ng serve --proxy-config proxy.json这个命令它将编译代码。你应该在控制台上看到类似的东西。 building modules 3/3 modules 0 active[HPM] Proxy created: /api -> http://localhost:8080 Subscribed to http-proxy events: [ 'error', 'close' ]

0
投票

当你运行angular和web api时,这些都在两个端口上运行。您需要在服务器上启用CORS策略。

如果您使用的是web api,则在项目上启用cors策略,它将解决您的问题。


0
投票

startup.cs类中,在两个方法ConfigureServicesConfigure()中添加以下语句。此解决方案与我合作,无需在Web浏览器上安装CORS:

public void ConfigureServices(IServiceCollection services)
    {
        // Add policy for CORS
        services.AddCors(options =>
        {
            options.AddPolicy("AllowAll",
                builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials();
                });
        });

       // You additional configurations here....
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors("AllowAll"); // Add this line here or inside if (env.IsDevelopment()) block

        if (env.IsDevelopment())
        {
            // app.UseCors("AllowAll");
            app.UseDeveloperExceptionPage();
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.