【发布时间】:2020-02-01 10:25:02
【问题描述】:
如何修复我的 React 和 spring 应用程序中的 CORS 错误。
我已经实现了一个简单的方法来获取用户列表。我已经使用邮递员测试了这个端点。现在我正在使用 fetch API 从我的 react js 应用程序中获取此列表。我在 Spring 后端添加了 @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 配置文件:-
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;
}
弹簧控制器:-
@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("*");
}
};
}
}
我想在下拉菜单中列出用户。任何帮助将不胜感激。
【问题讨论】:
-
你重启 Spring 应用了吗?
-
@MatthewGaiser 我确实重启了。
-
你得到什么错误?在邮递员中,您是否看到响应中的 cors 标头?
-
@acdcjunior 我没有在响应中看到 cors 标头。错误消息:-
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 -
您在邮递员收到的响应中看到
Access-Control-Allow-Origin标头吗?
标签: reactjs spring-boot