【发布时间】:2021-09-27 10:26:00
【问题描述】:
我用 spring boot 和 react 创建了一个简单的应用程序。我登录时从后端获得了 jwt 令牌。自动传递标头后,我需要使用该令牌访问数据。 (如下postmon ss)
这是我的反应代码
useEffect(()=>{
const config ={
headers:{
Authorization: 'Bearer '+ localStorage.getItem('token')
}
}
axios.get('http://localhost:8090/dashboard',config).then(res=>{
console.log(res);
})
})
这是我的弹簧控制器类
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class AuthController {
@Autowired
private UserRepository userRepository;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserService userService;
@Autowired
private JwtUtils jwtUtils;
@GetMapping("/dashboard")
public String testingToken(){
return "Welcome to dashboard.";
}
@PostMapping("/register")
private ResponseEntity<?> subscribeClient(@RequestBody AuthenticationRequest authenticationRequest){
String userName = authenticationRequest.getUserName();
String password = authenticationRequest.getPassword();
String userType = authenticationRequest.getUserType();
Users userModel = new Users();
userModel.setUserName(userName);
userModel.setPassword(password);
userModel.setUserType(userType);
try{
userRepository.save(userModel);
}catch (Exception e){
return ResponseEntity.ok(new AuthenticationResponse("Error while subscription."+ userName));
}
return ResponseEntity.ok(new AuthenticationResponse("Successfully authenticated."+ userName));
}
@PostMapping("/login")
private ResponseEntity<?> authenticateClient(@RequestBody AuthenticationRequest authenticationRequest){
String userName = authenticationRequest.getUserName();
String password = authenticationRequest.getPassword();
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName,password));
}catch (Exception e){
return ResponseEntity.ok(new AuthenticationResponse("Error during client authentication."+ userName));
}
UserDetails userDetails = userService.loadUserByUsername(userName);
String generatedToken = jwtUtils.generateToken(userDetails);
return ResponseEntity.ok(new AuthenticationResponse(generatedToken));
}
}
当我运行它时,控制台结果是
Access to XMLHttpRequest at 'http://localhost:8090/dashboard' from origin
'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
如何解决这个问题?
【问题讨论】:
-
cors 是春季回答最多的问题。请在此处询问之前使用谷歌。投票结束
标签: reactjs spring spring-boot spring-security