问题描述
这是后端配置
@Override
public void configure(AuthenticationManagerBuilder auth) {
try {
auth.inMemoryAuthentication()
.withUser("user1").password(bcpe.encode("123")).roles("USER")
.and()
.withUser("user2").password(bcpe.encode("123")).roles("USER","GUEST")
.and()
.withUser("user3").password(bcpe.encode("123")).roles("USER","GUEST","ADMIN");
} catch (Exception e) {
e.printstacktrace();
}
}
@Override
public void configure(HttpSecurity http) {
try {
http.csrf().disable().cors().disable();
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().permitAll();
} catch (Exception e) {
e.printstacktrace();
}
}
这是前端提取
var myHeaders = new Headers();
myHeaders.append("Authorization","Basic " + base64.encode("user3:123"));
myHeaders.append("Content-Type","application/json");
myHeaders.append("Cookie","JSESSIONID=9715BDB472F3B44BCE6ADEDD9FE90961");
var requestOptions = {
method: 'GET',headers: myHeaders,redirect: 'follow'
};
fetch("http://localhost:8080/admin/account",requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error',error));
我收到错误 Access to fetch at 'http://localhost:8080/admin/account' 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. If an opaque response serves your needs,set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
谢谢!
解决方法
我假设您使用的是 Google Chrome。由于安全准则,Chrome 不允许这样做。尝试安装以下插件:https://chrome.google.com/webstore/detail/moesif-origin-cors-change/digfbfaphojjndkpccljibejjbppifbc