No Access-Control-Allow-Origin header is present on the requested resource Spring Boot

I've found @CrossOrigin to be extremely finicky. You can try using just @CrossOrigin without any parameters as Alexander suggested.

You can also try adding a custom CorsFilter Bean to the class where you call SpringApplication.run(). That way you've essentially got full control over the filter and can add/remove methods if necessary.

Something like this:

@Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.setAllowedOrigins(Collections.singletonList("*")); config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept")); config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); }

Caros,

Por favor, sabem informar como posso resolver esse problema, parece está havendo um bloqueio para o vue acessar o json, agradeço qualquer ajuda.

No Access-Control-Allow-Origin header is present on the requested resource Spring Boot

package br.com.alura.mvc.mudi.api; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import br.com.alura.mvc.mudi.dto.RequisicaoNovaOferta; import br.com.alura.mvc.mudi.model.Oferta; import br.com.alura.mvc.mudi.model.Pedido; import br.com.alura.mvc.mudi.repository.PedidoRepository; @RestController @RequestMapping("/api/ofertas") public class OfertasRest { @Autowired private PedidoRepository pedidoRepository; @PostMapping public Oferta criaOferta(@RequestBody RequisicaoNovaOferta requisicao){ Optional<Pedido> pedidoBuscado = pedidoRepository.findById(requisicao.getPedidoId()); if(!pedidoBuscado.isPresent()){ return null; } Pedido pedido = pedidoBuscado.get(); Oferta nova = requisicao.toOferta(); nova.setPedido(pedido); pedido.getOfertas().add(nova); pedidoRepository.save(pedido); return nova; } } <!DOCTYPE html> <html> <head th:replace="~{base :: head('Meus Pedidos')}"></head> <body onload="onLoad()"> <div th:replace="~{base :: logo}"></div> <div class="container" id="ofertas"> <div th:replace="~{base :: titulo('Faça sua Oferta')}"></div> <div class="card mb-3" v-for="pedido in pedidos"> <div class="card-header alert-dark">{{pedido.nomeProduto}}</div> <div class="card_body"> <div class="row"> <div class="col-12 col-sm-7 mb-3"> <div>Produto</div> <div><a v-bind:href="pedido.urlProduto">{{pedido.nomeProduto}}</a></div> <div>Descrição</div> <div> <textarea class="form-control">{{pedido.descricao}}</textarea> </div> <div class="row mt-3"> <div class="col-md-5">Valor: <input class="form-control" v-model="pedido.valorNegociado"/></div> <div class="col-md-7">Data da entrega: <input class="form-control" v-model="pedido.dataDaEntrega"/></div> </div> <div class="mt-2"> <label>Comentário:</label> <textarea class="form-control" v-model="pedido.comentario"></textarea> </div> <button v-on:click="enviarOferta(pedido)" class="btn btn-primary mt-2">Enviar Oferta</button> </div> <div class="col-12 col-sm-4"> <div> <img class="img-thumbnail" v-bind:src="pedido.urlImagem"/> </div> </div> </div> </div> </div> </div> <script> function onLoad() { var app = new Vue( { el : '#ofertas', data : { pedidos : [] }, mounted () { axios .get('http://localhost:8080/api/pedidos/aguardando') .then(response => (this.pedidos = response.data)) } }); } </script> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </body> </html>

solução!

Depois de algumas pesquisas, descobri que o browser bloqueia o acesso se a url usada no script que roda no browser (javascript) for diferente da url da aplicação, então dependendo da maneira que acessar a aplicação, utilizar no script localhost ou 127.0.0.1

Blz? Usar a mesma base url (domínio) evita o problema de CORS, porém algumas vezes queremos permitir que domínios/hosts diferentes tenham acesso, pra isso definimos uma diretiva de CORS.

Não tenho experiencia com spring, mas acredito que você poderia olhar esse site:

https://spring.io/guides/gs/rest-service-cors/

How do I enable CORS policy in spring boot?

Enable CORS in Controller Method We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.

How do you add Access

For IIS6.
Open Internet Information Service (IIS) Manager..
Right click the site you want to enable CORS for and go to Properties..
Change to the HTTP Headers tab..
In the Custom HTTP headers section, click Add..
Enter Access-Control-Allow-Origin as the header name..
Enter * as the header value..
Click Ok twice..

How do I resolve the no Access

Open your distribution from the CloudFront console. Choose the Behaviors tab. Choose Create Behavior. Or, select an existing behavior, and then choose Edit..
Access-Control-Request-Headers..
Access-Control-Request-Method..
Origin..

How do I fix CORS header Access

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.