angular springboot跨域访问

来源:互联网 发布:linux ip地址映射 编辑:程序博客网 时间:2024/06/08 11:31

前端使用angular访问http://localhost:8080/people获取数据
控制台显示
这里写图片描述

XMLHttpRequest cannot load http://localhost:8080/people. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:4200’ is therefore not allowed access.

解决办法:
添加一个配置类,继承WebMvcConfigurerAdapter
重写addCorsMappings方法

@Configurationpublic class CorsConfiguration extends WebMvcConfigurerAdapter {    @Override    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/**")  //允许跨域访问的链接 "/**" 表示允许所有链接                .allowedMethods("*");           //允许的http方法(GET,PUT,POST,DELETE...),"*"表示允许所有方法    }}
0 0