如何修复React和Spring Web应用程序中的cors错误?

时间:2019-10-03 06:25:33

标签: reactjs spring-boot

如何修复React和spring应用程序中的CORS错误。

我已经实现了一种简单的方法来获取用户列表。我已经使用邮递员测试了此端点。现在,我使用fetch API从我的react js应用程序中获取此列表。我在春季后端添加了@CrossOrigin批注。我还在我的React应用程序中的package.json文件中添加了一个代理。

反应JS代码:-

import React from 'react';
import { Component } from 'react';

class DropDownUsers extends Component {
  state = {
    users : [],
    selectedUser : "",
    validationError : ""
  }

  componentDidMount() {

   fetch("http://localhost:8080/api/users")
    .then(data => {
      let usersFromApi = data.map(user => {
        return {
          value : user,
          display : user
        }})
      this.setState({ users : [{value: '', display: '(Choose the user)'}].concat(usersFromApi)});
    })
      .then((response) => {
        return response.json();
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <div>
        <select value={this.state.selectedUser}
                onChange={(e) => this.setState({selectedUser: e.target.value})}
         >
         {this.state.users.map((user) => <option key={user.value} value={user.value}> {user.display}</option>)}
        </select>
        <div style={{color:'red',marginTop:'5px'}}>
          {this.state.validationError}
        </div>
      </div>
    )
  }
}

export default DropDownUsers;

错误消息:-

Access to fetch at 'http://localhost:8080/api/users' from origin 'http://localhost:3001' 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

Spring Config文件:-

public ConfigurableServletWebServerFactory servletContainer() {
        final TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();

        if (ajpEnabled) {
            factory.setProtocol("AJP/1.3");

            factory.addConnectorCustomizers(connector -> {
                connector.setSecure(false);
                connector.setScheme("http");
                connector.setAllowTrace(true);
                connector.setPort(8009);
            });
        }

        return factory;
    }

Spring Controller:-

@Slf4j
@EnableLogging
@CrossOrigin(origins = "http://localhost:3001")
@Path("/users")
public class ListOfUsers {

    @Autowired
    DAO DAO;

    @GET
    @Produces(APPLICATION_JSON)
    public Response execute(@Valid ListOfUsersBean listOfUsersBean) {

        final Optional<List<ListOfUsersBean>> user = DAO.getTotalListOfUsers();
        return status(SC_OK).entity(user).build();
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*");
            }
        };
    }

}

我想在下拉菜单中列出用户。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

我能够解决问题。我必须添加在此页面中找到的CORSFilter类,如下所示:-https://stackoverflow.com/questions/23450494/how-to-enable-cross-domain-requests-on-jax-rs-web-services:-

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(final ContainerRequestContext requestContext,
                       final ContainerResponseContext cres) throws IOException {
        cres.getHeaders().add("Access-Control-Allow-Origin", "*");
        cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
        cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        cres.getHeaders().add("Access-Control-Max-Age", "1209600");
    }

}

答案 1 :(得分:1)

在配置文件中,如果您使用的是WebMvcConfigurer基本软件包,则应覆盖

    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }