1
votes

Spring Boot with React

Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'http://localhost:3000' has been blocked by CORS policy:

This is a contoller which return all district objects

Access to XMLHttpRequest at 'http://localhost:8080/ from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

package com.ministry.demo.controller;

import com.ministry.demo.model.District;
import com.ministry.demo.repository.DistrictRepository;
import com.ministry.demo.service.DistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(path = "district")
public class DistrictController {
    @Autowired
    DistrictService service;

    @GetMapping(path = "getAll")
    List<District> getAllDistrict(){
        return service.getAllDistricts();
    }
}
3

3 Answers

7
votes

I found an Answer

package com.ministry.demo.controller;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping(path = "district")
public class DistrictController {
    @Autowired
    DistrictService service;

    @GetMapping(path = "getAll")
    List<District> getAllDistrict(){
        return service.getAllDistricts();
    }
}
0
votes

If your backend and your app are not running on the same address your browser does normally not allow you to call your backend. This is intended to be a security feature.

To allow your browser to call your api add the Access-Control-**** headers to your backend response (when answering from Spring).

See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Most basic header that allows all origins:

Access-Control-Allow-Origin: *

Here is a tutorial for adding those headers in Spring: https://spring.io/guides/gs/rest-service-cors/

0
votes

MyConfiguration.java

@Configuration
public class MyConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*");
    }

}