React 让我说跨源请求被阻止:同源策略不允许读取远程资源http://localhost:8080/用户 http://localhost:8080/users。 (原因:CORS 标头“Access-Control-Allow-Origin”丢失)。
奇怪的是,它对我有用,但在没有对控制器代码进行任何更改的情况下它就停止工作了......
用户控制器.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});
});
}
它突然停止工作有什么原因吗?
edit:
我尝试创建一个干净的新 Maven 项目并将所有包复制到新项目中,现在它可以工作了,但我仍然不知道为什么它停止工作,代码是相同的,现在它可以工作了。
如果您正在使用春季安全并希望 CORS 在您的项目中全局存在,然后尝试将其添加到配置中:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors()
.and()
........ other config
}
但在此之前请尝试以下方法。申请CORS在类级别使用它像这样:
@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@Controller
public class SomeController{
}
或者在方法级别使用它,如下所示:
@CrossOrigin("http://example.com")
@RequestMapping("/some")
public Account retrieve() {
// ...
}
OR
@CrossOrigin(origins = "*")
@RequestMapping("/some")
public Account retrieve() {
// ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)