繁体   English   中英

Cross Origin 如何在 Spring Boot 和 Angular Cli 之间工作?

[英]How does Cross Origin works between Spring Boot and Angular Cli?

我正在关注本教程Spring/Angular

当我运行我的应用程序时,我收到此错误:

CORS 策略已阻止在 ' http://localhost:8080/api/employees ' 从源 ' http://localhost:4200 ' 访问 XMLHttpRequest 请求的资源。

我提出了关于 Cross Origin 的不同问题,但我不知道在哪里插入它以及在它上面插入什么,因为在教程中从未显示或使用它。

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CORSConfiguration  {

   @SuppressWarnings("deprecation")
    @Bean
        public WebMvcConfigurer corsConfigurer()
        {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "DELETE", "OPTIONS");
                }    
            };
        }
}

你可以添加一个proxy.config.json

{
  "/application1/rest": {
    "target": "http://localhost:8060/",
    "secure": false
  },
 "/anotherapp": {
    "target": "http://localhost:8060/",
    "secure": false
  }  
}

然后使用:

directory\angular> ng serve --proxy-config proxy.config.json

跨源与前端无关。 您需要做的就是在后端允许前端的 URL。 通常我们在后端写一个 CORS 过滤器,我们允许前端 url 在那里。

按照本教程使用 Spring 进行 CORS

更新

我在服务器端 (Spring) 中创建了一个带有 @Configuration 注释的类:

package it.si2001.SpringBootJPACRUDExample.configuration;

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 CORSConfiguration implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedHeaders("*")
                .allowedMethods("GET", "POST", "DELETE");
    }
}//close class
In Tomcat `web.xml` file set these cors.
`<filter>
    <filter - name> CorsFilter </filter-name> 
    <filter - class> org.apache.catalina.filters.CorsFilter </filter-class> 
</filter>
<filter - mapping>
    <filter - name> CorsFilter </filter-name>
    <url - pattern>/*</url-pattern>
</filter-mapping>`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM