java - 无法修复 CORS 错误(角度 + java spring)
问题描述
我正在尝试通过前端从后端请求数据,但出现错误:
Access to XMLHttpRequest at 'http://localhost:8081/api/transactions/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我可以通过邮递员获取数据,但不是我的前端。我正在使用角度和弹簧靴。
我的应用程序.java:
@EnableJpaRepositories
@EntityScan
@SpringBootApplication
public class KoalaTreeAccountingApplication {
public static void main(String[] args) {
SpringApplication.run(KoalaTreeAccountingApplication.class, args);
}
}
我的安全配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.permitAll()
.and().csrf().disable();
}
}
我的服务以角度进行 http 调用:
@Injectable({
providedIn: 'root'
})
export class TransactionService {
baseUrl = 'http://localhost:8081/api/';
transactionUrl = this.baseUrl + 'transactions/';
constructor(private http: HttpClient, private logger : Logger){ }
getAllTransactions() : Observable<Transaction[]> {
this.logger.log("Request all transactions");
return this.http.get<Transaction[]>(this.transactionUrl);
}
getTransactionById(id : number) : Observable<Transaction> {
this.logger.log("Request transaction " + id);
return this.http.get<Transaction>(this.transactionUrl + id);
}
}
编辑:我已经尝试过
https://spring.io/guides/gs/rest-service-cors/
Spring Security CORS 过滤器不工作
Spring-boot 的安全配置
https://stackoverflow.com/a/31748398/12025088
Protip:在更改后重新运行应用程序之前进行全新安装。我是个白痴。
通过使用它而不是 SecurityConfig.java 来修复:
@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "36000");
response.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
解决方案
您需要在您想要允许的 RestController 方法上配置 CORS。CORS 是服务器响应。
@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/")
public List<Transaction> findAllTransactions() {
return transactionService.findAllTransactions(); }
}
推荐阅读
- c# - 将数据从 1 个场景传输到 2 个场景
- algorithm - 联合查找和广度优先搜索的优缺点是什么?
- gradle - 将 Micrometer for Prometheus 库添加到 Grails 项目会在运行时引发 NoClassDefFoundError
- spring-boot - 从 Spring Data 调用存储过程时出错
- python - 高斯过程回归:将输入映射到时间序列
- javascript - Socket.io 和 Chat 应用程序出现 ERR_CONNECTION_REFUSED 错误
- javascript - Styled Components 如何转发 props?
- flutter - 如何解决未处理的异常:类型'String'不是'index'类型'int'的子类型
- java - 休眠限制以在列表中使用类似子句进行搜索
- node.js - onCall 云函数不要等待承诺完成