我有使用Angular 8和spring boot的Web应用程序,并使用docker在EC2中部署了
如果我在rest调用中使用EC2实例的公共IP,则应用程序运行正常
http://54.172.42.170:8080/test/getMessage
但是如果我在其余网址中使用本地主机,则会失败
http://localhost:8080/test/getMessage
错误消息
Access to XMLHttpRequest at 'http://localhost:8080/test/getMessage' from origin 'http://54.172.42.170:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我想使用localhost,所以每次EC2实例重新启动时都不需要更改ip
答案 0 :(得分:0)
Angular应用程序正在浏览器中运行,因此它必须引用后端的公共IP或主机名。因此,您必须:
您观察到的错误会误导您,因为您的计算机上正在运行一个后端实例。在随机用户的浏览器上,它只会因诸如ERR_CONNECTION_REFUSED之类的错误而失败
答案 1 :(得分:-1)
看起来您的前端已从54.172.42.170提供服务,您的后端正在本地计算机上运行。这是正确的吗?
您可以配置Spring Boot App,使其允许您的原点54.172.42.170从交叉原点访问。像这样:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://54.172.42.170:8080");
}
}
您可以在Spring文档https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/cors.html#cors
中找到有关CORS的更多信息。