How to Catch JSON Data with Angular

Asked

Viewed 655 times

1

I am studying angular and I am trying to receive data in JSON format from a webservice, but is with the following error:

Xmlhttprequest cannot load http://localhost:8080/Newspaper/data/newspaper. In the 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost' is therefore not allowed access.

Follow my Cod down.

app.controller("jornalCtrl", function($scope, $http) { 

    var url = 'http://localhost:8080/newspaper/dados/jornal';

    $http({
        method: 'JSONP',
        url: url,
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Origin': '*'
        },
        params:   {
            format: 'jsonp',
            callback: 'JSON_CALLBACK'
        }
    })
    .then(function successCallback(response) {
        $scope.jornais = response.jornais.jornal; 
    },
    function errorCallback(response) {
        $scope.content = "Something went wrong!";
    });
});
  • This Chrome app will save you: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

  • Dude I believe you can use a direct HTTP protocol instead of Xmlhttprequest because it works in a similar and more practical way for conversations between server and client;

2 answers

1

This is security provided by browsers that do not allow you to access a server that has not allowed you, your host, dns, ip to consume it.

The webservice would have to enable localhost to access it, consume its services.

1

You need to enable the CORS (sorry, I did not find the same documentation in Portuguese) in your service. Then you will need to search in the documentation of the service you are using to allow it, in Spring Boot for example it is necessary to include the annotation:

@CrossOrigin(origins = "*")

Access control should really be released on the server. A common error is trying to allow CORS on the client.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.