【发布时间】:2020-07-19 15:03:15
【问题描述】:
我正在尝试通过前端从后端请求数据,但出现错误:
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 filter not working
Security configuration with 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() {
}
}
【问题讨论】:
-
你看过前 3 个链接了吗? google.com/search?q=how+to+fix+cors
-
@ArnaudClaudel 那些没有帮助。我试过spring.io/guides/gs/rest-service-cors,但它给了我错误
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. -
@Imranmadbar 我已经用你发给我的线程中的配置替换了我的安全配置,但它给出了同样的错误。
-
请问可以提供资源控制器的代码吗?我说的是在 .../api/transactions url 上运行 GET 时调用的后端方法。