Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 246
Nilupul Heshan Avatar asked Dec 07 '25 06:12

Nilupul Heshan


2 Answers

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();
    }
}
like image 68
Nilupul Heshan Avatar answered Dec 08 '25 20:12

Nilupul Heshan


MyConfiguration.java

@Configuration
public class MyConfiguration implements WebMvcConfigurer {

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

}
like image 45
Matheus Cirillo Avatar answered Dec 08 '25 19:12

Matheus Cirillo