reactjsspring-bootcontrollercors-anywhere

origin has been blocked by CORS policy Spring boot and React


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();
    }
}

Solution

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