被 CORS 策略阻止:在 docker 实施后没有'Access-Control-Allow-Origin'标头



我最近创建了一个简单的ReactJs+Springboot应用程序。通过单击按钮,它调用springboot应用程序中的一个方法。在我当地,它运行得很好。之后,我为两个应用程序创建了docker文件,并使用docker compose文件将两者组合在一起,并部署在docker中。我也用过nginx服务器。所有这些都在Docker中运行,但当我点击react UI中的按钮时,它不会调用springboot中的方法。它在web控制台中引发以下错误。

Access to fetch at 'http://localhost:8080/api/roll' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
GET http://localhost:8080/api/roll net::ERR_FAILED 502

在我的react应用程序中,Package.json。>"proxy": "http://localhost:8080",我删除并尝试。不起作用

在反应页面中,

await fetch('http://localhost:8080/api/roll')
.then(response => response.json())
.then(data => {

我同时尝试了'http://localhost:8080/api/roll''api/roll'。但它没有起作用。

在Springboot项目中,我尝试了以下内容。

添加@CrossOrigin,但没有成功。

@RestController
@CrossOrigin
@RequestMapping("/api")
public class GameController {



@GetMapping("/roll")
Public Player rollingDice()

public class CORSResponseFilter implements ContainerResponseFilter {
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
MultivaluedMap<String, Object> headers = responseContext.getHeaders();
headers.add("Access-Control-Allow-Origin", "*");
headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia");
}
}

@Configuration
@Primary
public class DefaultJerseyServletConfig {
@Bean
public ServletRegistrationBean<Servlet> defaultJersey(RestResourceMainConfig serviceConfig) {
ServletRegistrationBean<Servlet> defaultJersey = new ServletRegistrationBean<Servlet>(
new ServletContainer(serviceConfig));
defaultJersey.addUrlMappings("/api/*");
defaultJersey.setName("DefaultJersey");
defaultJersey.setLoadOnStartup(0);
return defaultJersey;
}
}

以上这些对我都不起作用。有人能帮我解决这个问题吗?

我认为您应该在Access-Control-Allow-Origin中编写前端URL,这里是http://localhost:3000

此外,您必须在前端使用Credentitails 提出请求

相关内容

最新更新