首页 > 解决方案 > 无法修复 CORS 错误(角度 + java spring)

问题描述

我正在尝试通过前端从后端请求数据,但出现错误:

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

我可以通过邮递员获取数据,但不是我的前端。我正在使用角度和弹簧靴。
我的应用程序.java:

@EnableJpaRepositories
@EntityScan
@SpringBootApplication
public class KoalaTreeAccountingApplication {

    public static void main(String[] args) {
        SpringApplication.run(KoalaTreeAccountingApplication.class, args);
    }

}

我的安全配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest()
                .permitAll()
                .and().csrf().disable();
    }
}

我的服务以角度进行 http 调用:

@Injectable({
    providedIn: 'root'
})
export class TransactionService {
    baseUrl = 'http://localhost:8081/api/';
    transactionUrl = this.baseUrl + 'transactions/';

    constructor(private http: HttpClient, private logger : Logger){ }

    getAllTransactions() : Observable<Transaction[]> {
        this.logger.log("Request all transactions");
        return this.http.get<Transaction[]>(this.transactionUrl);
    }

    getTransactionById(id : number) : Observable<Transaction> {
        this.logger.log("Request transaction " + id);
        return this.http.get<Transaction>(this.transactionUrl + id);
    }
}

编辑:我已经尝试过
https://spring.io/guides/gs/rest-service-cors/
Spring Security CORS 过滤器不工作
Spring-boot 的安全配置
https://stackoverflow.com/a/31748398/12025088

Protip:在更改后重新运行应用程序之前进行全新安装。我是个白痴。

通过使用它而不是 SecurityConfig.java 来修复:

@Component
public class SimpleCORSFilter implements Filter {
    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-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "36000");
        response.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }
}

标签: javaangularspringcors

解决方案


您需要在您想要允许的 RestController 方法上配置 CORS。CORS 是服务器响应。


    @CrossOrigin(origins = "http://localhost:4200")
    @GetMapping("/") 
    public List<Transaction> findAllTransactions() { 
        return transactionService.findAllTransactions(); } 
    } 

推荐阅读