-1

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/
Spring Security CORS filter not working
Security configuration with Spring-boot
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() {
    }
}
therealsyh
  • 31
  • 8
  • Have you looked at the first 3 links? https://www.google.com/search?q=how+to+fix+cors – Arnaud Claudel Apr 07 '20 at 12:14
  • You may ask for this: https://stackoverflow.com/a/59561352/8403689 – Imranmadbar Apr 07 '20 at 12:16
  • @ArnaudClaudel those didn't help. I've tried https://spring.io/guides/gs/rest-service-cors/ but it gives me 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.``` – therealsyh Apr 07 '20 at 12:21
  • @Imranmadbar I've replaced my security config with the config in the thread you sent me, but it gives the same error. – therealsyh Apr 07 '20 at 12:24
  • Please, can you provide the code of the resource controller? I'm talking about the backend method that is being called when you run a GET on the .../api/transactions url. – lucasdclopes Apr 07 '20 at 12:58
  • @lucasdclopes it's nothing special, but here it is ``` @RestController @RequestMapping(value = "/api/transactions") public class TransactionController { @Autowired private TransactionService transactionService; @GetMapping("/") public List findAllTransactions() { return transactionService.findAllTransactions(); } } ``` – therealsyh Apr 07 '20 at 20:06

1 Answers1

0

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(); } 
    } 
lucasdclopes
  • 147
  • 9