英文:
Can't fix CORS error (angular + java spring)
问题
以下是您要翻译的内容:
我正在尝试通过前端从后端请求数据,但是我收到了以下错误:
从源 'http://localhost:4200' 到 'http://localhost:8081/api/transactions/' 的 XMLHttpRequest 访问已被 CORS 策略阻止:在请求的资源上不存在 'Access-Control-Allow-Origin' 标头。
我可以使用 Postman 获取数据,但无法在前端获取。我正在使用 Angular 和 Spring Boot。
我的 application.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();
}
}
我在 Angular 中用于进行 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("请求所有交易");
return this.http.get<Transaction[]>(this.transactionUrl);
}
getTransactionById(id : number) : Observable<Transaction> {
this.logger.log("请求交易 " + id);
return this.http.get<Transaction>(this.transactionUrl + id);
}
}
编辑:我尝试过以下链接中的方法:
https://spring.io/guides/gs/rest-service-cors/
https://stackoverflow.com/questions/38250192/spring-security-cors-filter-not-working?rq=1
https://stackoverflow.com/questions/25633477/security-configuration-with-spring-boot?rq=1
https://stackoverflow.com/a/31748398/12025088
专业提示:在更改后重新运行应用程序之前进行“clean install”。我真是个白痴。
通过使用以下代码修复,取代 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() {
}
}
希望这对您有所帮助!
英文:
I'm trying to request data from my backend through my frontend, but I'm getting the error:
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.
I am able to get the data with postman, but not my frontend. I'm using angular and spring boot.
My application.java:
@EnableJpaRepositories
@EntityScan
@SpringBootApplication
public class KoalaTreeAccountingApplication {
public static void main(String[] args) {
SpringApplication.run(KoalaTreeAccountingApplication.class, args);
}
}
My security config:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.permitAll()
.and().csrf().disable();
}
}
My service to make the http call in angular:
@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);
}
}
Edit: I've tried
https://spring.io/guides/gs/rest-service-cors/
https://stackoverflow.com/questions/38250192/spring-security-cors-filter-not-working?rq=1
https://stackoverflow.com/questions/25633477/security-configuration-with-spring-boot?rq=1
https://stackoverflow.com/a/31748398/12025088
Protip: clean install before re-running the application after a change. I'm an idiot.
Fixed by using this instead of 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() {
}
}
答案1
得分: 0
@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/")
public List<Transaction> findAllTransactions() {
return transactionService.findAllTransactions();
}
英文:
You need to configure CORS on the methods of your RestController that you want to allow it. CORS is a server response.
@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/")
public List<Transaction> findAllTransactions() {
return transactionService.findAllTransactions(); }
}
专注分享java语言的经验与见解,让所有开发者获益!
评论