codememo

원산지 'http://localhost:4200'이(가) Angular7의 CORS 정책에 의해 차단되었습니다.

tipmemo 2023. 8. 1. 20:34
반응형

원산지 'http://localhost:4200'이(가) Angular7의 CORS 정책에 의해 차단되었습니다.

저는 http://5.160.2.148:8091/api/trainTicketing/city/Findrest for citys를 제 각진 프로젝트에서 사용하고 싶습니다.
저는 제 프로젝트에서 7.2.15 버전의 앵글을 사용했습니다.
오류와 함께 이: httpClient throw는 URL입니다.

 Access to XMLHttpRequest at 'http://5.160.2.148:8091/api/trainTicketing/city/findAll' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

브라우저와 우체부에 url을 입력하면 올바르게 작동합니다.

왜요?

솔루션 1 - 수신 요청을 수락하려면 백엔드를 변경해야 합니다.

솔루션 2 - Angular 프록시 사용은 여기를 참조하십시오.

이 작업은 다음 용도로만 수행됩니다.ng serve에서 프록시를 사용할 수 없습니다.ng build

솔루션 3 - 백엔드가 다음과 같은 와일드카드 도메인의 요청을 수락하는 경우*.mydomain.example 그런다편수있다니습할집음▁your다를 할 수 .hosts을 을 추가합니다.127.0.0.1 local.mydomain.example에서 그안서에 그고나대당신브신라서에저우의서리▁in서▁instead에저브▁then라우▁your.localhost:4200를 입력하십시오.local.mydomain.example:4200

참고: 우체부를 통해 작동하는 이유는 집배원이 브라우저가 전송하는 동안 비행 전 요청을 보내지 않기 때문입니다.

.NET CORE 3.1의 경우

코르스 미들웨어를 추가하기 직전에 https 리디렉션을 사용하고 있었고 순서를 변경하여 문제를 해결할 수 있었습니다.

내 말은 다음과 같습니다.

변경 내용:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseHttpsRedirection();  

        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

      ...

     }

대상:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

        app.UseHttpsRedirection(); 

      ...

     }

참고로, 생산 단계에서 모든 출처와 방법의 요청을 허용하는 것은 좋은 생각이 아닐 수도 있습니다. 생산 단계에서 당신은 당신 자신의 코르스 정책을 작성해야 합니다.

스프링 부트를 사용하는 경우 @CrossOrigin 주석에 오리진 링크를 추가해야 합니다.

@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/yourPath")

자세한 지침은 https://spring.io/guides/gs/rest-service-cors/ 에서 확인할 수 있습니다.

솔루션은 이 헤더를 서버 응답에 추가해야 합니다.

'Access-Control-Allow-Origin', '*'
'Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT'

서버에 액세스할 수 있는 경우 추가할 수 있습니다. 그러면 문제가 해결됩니다.

OR

다음 URL 앞에 이 내용을 포함할 수 있습니다.

https://cors-anywhere.herokuapp.com/

당신들은 심지어 우체부도 코르스 정책 문제를 제기하지 않는 앵귤러 사이드를 잘합니다.이러한 유형의 문제는 주요한 경우 백엔드에서 해결됩니다.

Spring boot를 사용하는 경우 컨트롤러 클래스 또는 특정 방법에 주석을 배치하여 이 문제를 방지할 수 있습니다.

@CrossOrigin(origins = "http://localhost:4200")

스프링 부트로 글로벌 구성하는 경우 다음 두 가지 클래스를 구성합니다.

`

@EnableWebSecurity
@AllArgsConstructor

public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
    public void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity.csrf().disable()
        .authorizeRequests()
        .antMatchers("/api1/**").permitAll()
        .antMatchers("/api2/**").permitAll()
        .antMatchers("/api3/**").permitAll()
        
}
`

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry corsRegistry) {
        corsRegistry.addMapping("/**")
                .allowedOrigins("http://localhost:4200")
                .allowedMethods("*")
                .maxAge(3600L)
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .allowCredentials(true);
    }

개발 중 임시 테스트의 경우 이렇게 비활성화된 웹 보안으로 크롬을 열어 비활성화할 수 있습니다.

명령줄 터미널을 열고 크롬이 설치된 폴더로 이동합니다.C:\프로그램 파일(x86)\Google\크롬\응용 프로그램

다음 명령을 입력합니다.

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

웹 보안이 비활성화된 새 브라우저 창이 열립니다.앱 테스트용으로만 사용하십시오.

다음 단계를 수행합니다.

  1. cors 의존성을 추가합니다. 프로젝트 디렉토리 내의 cli에 다음을 입력합니다.

npm install --save cors

  1. 프로젝트 내부에 모듈 포함

var cors = require('cors');

  1. 마지막으로 미들웨어로 사용합니다.

app.use(cors());

WebAPI에서 Startup.cs .

app.UseCors(options => options.AllowAnyOrigin());  

서비스 구성 방법:

services.AddCors(c =>  
{  
    c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());  
});

컨트롤러:

[HttpGet]  
     [Route("GetAllAuthor")]  
     [EnableCors("AllowOrigin")] 

프로젝트가 .net Core 3.1 API 프로젝트인 경우.

.net core 프로젝트의 Startup.cs 을 다음으로 업데이트합니다.

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
    readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(MyAllowSpecificOrigins,
            builder =>
            {
                builder.WithOrigins("http://localhost:53135",
                                    "http://localhost:4200"
                                    )
                                    .AllowAnyHeader()
                                    .AllowAnyMethod();
            });
        });
        services.AddDbContext<CIVDataContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("CIVDatabaseConnection")));
        services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors(MyAllowSpecificOrigins);

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

       
    }
}

위해서nodejs하세요.

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

클래스를 만들고 스프링 부트 응용 프로그램에 아래 구성을 추가합니다.

    package com.myapp.springboot.configs;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class WebMvcConfiguration implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/*").
            allowedOrigins("*").
            allowedMethods("*").
            allowedHeaders("*").
            allowCredentials(true);
        }
    }

1: WebMvcConfig 클래스를 만들고 WebMvcConfig에서 표시된 대로 확장하고 addCorsMappings 메서드를 재정의합니다.

2: 크로스 오리진을 허용하려면 메인 스프링 클래스와 함께 로드되어야 하므로 @Configuration 주석을 작성하는 것을 잊지 마십시오.

  @Configuration
    public class WebMvcCofig implements WebMvcConfigurer{
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/*")
                    .allowedOrigins("*")
                    .allowedMethods("*")
                    .allowedHeaders("*")
                    .allowCredentials(true);
        }
    }

위에 주어진 솔루션을 모두 시도해보고 nodejs 백엔드를 사용하면서 작업을 했지만 아쉽게도 파이썬으로 작업을 하다보니 플러그인 Allow CORS, 적어도 이 플러그인이 도움이 되었습니다.

서버 측 코딩에 스프링 부트를 사용하는 경우 서블릿 필터를 추가하고 스프링 부트 응용 프로그램의 다음 코드를 추가하십시오.그건 작동할 거야.추가 중"Access-Control-Allow-Headers", "*"필수 항목입니다.proxy.conf.json을 생성할 필요가 없습니다.

    @Component
@Order(1)
public class MyProjectFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PATCH,DELETE,PUT,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Max-Age", "86400");
        chain.doFilter(req, res);
    }
}

경우 Angular 및 Spring Boot를 사용하여 SecurityConfig에서 이 문제를 해결했습니다.

http.csrf().disable().cors().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/register")
            .anonymous()
            .anyRequest().authenticated()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

또는 해당 줄을 다음으로 바꿉니다.

http.csrf().disable().cors().and()

그리고 다른 테스트 옵션은 pom.xml에서 종속성을 삭제하고 다른 코드가 종속되는 입니다.Spring에서 보안을 해제하는 것과 같습니다.

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
     <version>2.3.3.RELEASE</version>
</dependency>

나는 익스프레스 서버에 있는 나의 API에 아래 문장을 추가하려고 시도했고 그것은 Angular8과 함께 작동했습니다.

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET , PUT , POST , DELETE");
    res.header("Access-Control-Allow-Headers", "Content-Type, x-requested-with");
    next(); // Important
})

Spring boot 2를 사용하는 경우 컨트롤러 클래스에 CrossOrigin 주석을 추가할 수 있습니다.

@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)

그것은 나에게 효과가 있었습니다!

봄 부팅에서 CORs 문제를 처리하는 방법은 매우 많습니다. 가장 쉬운 방법은 컨트롤러 위에 @CrossOrigin 주석을 놓는 것입니다. 리소스 java 파일에 있을 수 있습니다. 시도해 보십시오.

@CrossOrigin(origins= {"*"}, maxAge = 4800, allowCredentials = "false" @RestController

자세한 내용은 스프링 부트 CORs 문서를 참조하십시오.감사해요.

Dotnet Core와 함께 Angular를 사용하는 경우:

수업 중 Startup.cs

서비스 구성 방법에 따라 다음을 추가합니다.

services.AddCors();

방법에 따라 추가 구성

app.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:4200"));
  • 스프링 부트 응용 프로그램을 사용하는 경우 컨트롤러에 @CrossOrigin을 추가하고 import org.springframework.web.bind.notation 문을 가져오기만 하면 됩니다.CrossOrigin: 응용프로그램을 설정하고 다시 실행합니다.

JAVA CROSS 정책의 일반 REST API

@GET
@Path("getsample")
@Produces(MediaType.APPLICATION_JSON)
public Response getOptions() {
       Map<String,String> map=new HashMap<String,String>();
       // map.put("response",res); 
        map.put("name","Ajay");
         map.put("id","20");
         map.put("clg", "SLICA");
     
  return Response.ok()
    .header("Access-Control-Allow-Origin", "*")
    .header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
    .header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
    .entity(map)    
    .build();
  
}

네스티스

app.enableCors({ origin: "*" });

모든 오리진을 허용합니다.개발 모드에서만 허용하는 것이 좋습니다.

매핑 주석이 둘 이상인 경우(예:

@RequestMapping("/api/v1/")

반에서 1등을 하고 그리고

@GetMapping("/employees")

메소드 위 등에서 각 메소드에 대해 아래 코드를 작성할 필요가 없습니다. 클래스의 맨 위에 이 코드를 작성하면 충분합니다.

@CrossOrigin(origins = "http://localhost:4200")

나의 실수 @CrossOrigin(origins = "/http://localhost:4200", maxAge = 3600).

슬래시를 제거하여 수정됨 @CrossOrigin(origins = "http://localhost:4200", maxAge = 3600).

아래와 같이 컨트롤러 클래스에 @CrossOrigin("*") 주석을 추가합니다.

@RestController
@CrossOrigin("*")
public class UserController {
  @Autowired
  UserService userService;

  @PostMapping("/user")
  public boolean createUser(@RequestBody User user) {
    return userService.createUser(user);
  }
}

이 경우 오류가 발생했습니다.

Access to XMLHttpRequest at 'localhost:5000/graphql' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, brave, chrome-untrusted, https.

URL에 프로토콜(http 또는 https)을 포함해야 합니다.

const uri = 'http://localhost:5000/graphql'; // 

노드를 백엔드로 사용하는 경우 이 기능을 사용할 수 있습니다.Node.js의 server.js "API" 측에 이러한 행을 추가하기만 하면 "cors"를 설치할 수 있습니다.

const express = require('express');
const app = express();
app.use(express.json());
var cors = require('cors');
app.use(cors());

혹시 fireBase를 데이터베이스로 사용하고 있다면 링크 끝에 ".json"을 추가해야 합니다. 이것으로 문제가 해결되었습니다.

코르스 오류: https://uar-test-bd448-default-rtdb.firebaseio.com/rules

오류 없음: https://uar-test-bd448-default-rtdb.firebaseio.com/rules.**json**

Nodejs(백엔드)를 응용 프로그램 각도와 함께 사용하는 경우 NodeJsnpm install --save cors

var cors = required cors('';

app.use(앱);

Access to XMLHttpRequest at 'http://localhost:8080/getuser' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

1단계: Frontend 파트에 AuthInterceptor를 추가해야 합니다.

파일 auth.interceptor.ts->

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { LoginService } from "./login.service";


@Injectable({
    providedIn: 'root'
})
export class AuthInterceptor implements HttpInterceptor {

    constructor(private loginservice: LoginService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


        const token = this.loginservice.getToken();

        console.log("interceptor", token);

        if (token != null) {
            console.log("hello");

            req = req.clone(
                {
                    setHeaders: {
                        'Content-Type': 'application/json; charset=utf-8',
                        'Accept': 'application/json',
                        'Authorization': `Bearer ${token}`
                    }
                }
            )
        }
        return next.handle(req);

    }

}

그런 다음 저장하고 다시 실행합니다.동일한 문제가 발생할 경우 다음 단계를 수행합니다.

MySecurityConfig 파일에 구성 방법이 포함되도록 백엔드에서 SpringBoot을 사용하는 경우. 구성 방법 ->

public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .cors().disbale()
            .authorizeRequests()
            .antMatchers("/token")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(entrypoint)
            ;
        
        
    // if the problem not solve so change .cors().disable() -> .cors()   only   

    }

언급URL : https://stackoverflow.com/questions/56328474/origin-http-localhost4200-has-been-blocked-by-cors-policy-in-angular7

반응형