@CrossOrigin configures cross-origin resource sharing (CORS) so a browser-based client served from another host or port can consume a Spring API. section 7.1.1
Listing 7.1 A RESTful controller for taco design API requests
package tacos.web.api;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
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 tacos.Taco;
import tacos.data.TacoRepository;
@RestController
@RequestMapping(path="/api/tacos", #1
produces="application/json")
@CrossOrigin(origins="http://tacocloud:8080") #2
public class TacoController {
private TacoRepository tacoRepo;
public TacoController(TacoRepository tacoRepo) {
this.tacoRepo = tacoRepo;
}
@GetMapping(params="recent")
public Iterable<Taco> recentTacos() { #3
PageRequest page = PageRequest.of(
0, 12, Sort.by("createdAt").descending());
return tacoRepo.findAll(page).getContent();
}
}
See the complete TacoController example, where @CrossOrigin is placed on a REST controller alongside its API path and JSON response configuration. section 7.1.1
Allowing a separate frontend
A Taco Cloud API can allow a client at http://tacocloud:8080 by declaring @CrossOrigin(origins="http://tacocloud:8080") above TacoController. Multiple origins can be supplied as an array, such as http://tacocloud:8080 and http://tacocloud.com. section 7.1.1
