无法修复CORS错误(angular + java spring)

huangapple 未分类评论47阅读模式
英文:

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 &#39;http://localhost:8081/api/transactions/&#39; from origin &#39;http://localhost:4200&#39; has been blocked by CORS policy: No &#39;Access-Control-Allow-Origin&#39; 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: &#39;root&#39;
})
export class TransactionService {
    baseUrl = &#39;http://localhost:8081/api/&#39;;
    transactionUrl = this.baseUrl + &#39;transactions/&#39;;
    
    constructor(private http: HttpClient, private logger : Logger){ }

    getAllTransactions() : Observable&lt;Transaction[]&gt; {
        this.logger.log(&quot;Request all transactions&quot;);
        return this.http.get&lt;Transaction[]&gt;(this.transactionUrl);
    }

    getTransactionById(id : number) : Observable&lt;Transaction&gt; {
        this.logger.log(&quot;Request transaction &quot; + id);
        return this.http.get&lt;Transaction&gt;(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(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;);
        response.setHeader(&quot;Access-Control-Allow-Methods&quot;, &quot;POST, GET, OPTIONS, DELETE, PUT&quot;);
        response.setHeader(&quot;Access-Control-Max-Age&quot;, &quot;36000&quot;);
        response.setHeader(&quot;Access-Control-Allow-Headers&quot;, &quot;origin, content-type, accept&quot;);
        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 = &quot;http://localhost:4200&quot;)
	@GetMapping(&quot;/&quot;) 
	public List&lt;Transaction&gt; findAllTransactions() { 
		return transactionService.findAllTransactions(); } 
	} 

huangapple
  • 本文由 发表于 2020年4月7日 20:09:09
  • 转载请务必保留本文链接:https://java.coder-hub.com/61079723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定