【发布时间】:2018-12-05 21:55:38
【问题描述】:
React 让我说 Cross-Origin Request Blocked: The Same Origin Policy 不允许读取http://localhost:8080/users 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。
奇怪的认为它对我有用并且它停止工作而没有对控制器代码进行任何更改......
UserController.java
@RestController
@CrossOrigin
@RequestMapping(value = "/users")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
private User findOne(@PathVariable("userId") Integer userId) {
return userService.findOne(userId);
}
@RequestMapping(method = RequestMethod.GET)
private List<User> findAll() {
return userService.findAll();
}
@RequestMapping(method = RequestMethod.POST)
private User create(@RequestBody User user) {
user.setId(null); // To ensure we create instead of update
return userService.save(user);
}
@RequestMapping(value = "/{userId}", method = RequestMethod.PUT)
private User update(@PathVariable("userId") Integer userId, @RequestBody User user) {
user.setId(userId); // To ensure we update instead of create
return userService.save(user);
}
@RequestMapping(value = "/{userId}", method = RequestMethod.DELETE)
private void delete(@PathVariable("userId") Integer userId) {
final User user = userService.findOne(userId);
userService.delete(user);
}
}
这是我对 React 的理解
fetch('http://localhost:8080/users', {
method: 'GET',
headers: {
'content-type': 'application/json'
},
}).then(response => { return response.json();
}).then(data => {
this.setState({users:data});
});
}
它突然停止工作的任何原因?
编辑:
我尝试制作一个干净的新maven项目并将所有包复制到新项目中,现在它可以工作了,但我仍然不知道它为什么停止工作,代码是一样的,现在它可以工作了。
【问题讨论】:
-
对于 spring @CrossOrigin,默认 maxAge 为 30 分钟,尝试增加该值
-
我没用,我做了一个新的 maven 项目并复制了所有文件,现在它可以工作了,所有代码都一样,所以我真的不知道发生了什么,我要去编辑主帖
-
你是否改变了你的 spring 版本或类似的东西?
-
不,我使用了相同的 maven 配置
-
在 react 中,之前你使用 usr proxy 现在你在 fetch api 中使用完整路径,是这样吗?
标签: spring spring-mvc cors