Angular 1 reading JSON cross-Domain

Asked

Viewed 93 times

1

Guys having a small problem with angular and wanted to know if someone can help me, I was asked the following task to make a shelf from products of an external JSON (where has all the info of each product).

const API_URL = '/caminho/para/JSON.json';
var app = angular.module('root', []);
app.controller('testCtrl', function($scope, $http){
  $http({
  method: 'JSONP',
    url: API_URL
  }).then(function (success){
    $scope.content = "Something went right";
   },function (error){
    $scope.content = "Something went wrong";
   });
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
</head>
<body>
<div class="container" ng-app="root">
  <h1 ng-controller="testCtrl">
    {{content}}
  </h1>
</div>
</body>
</html>

<--JSON EXCERPT-->

[
  {
    "productId": "2000646",
    "productName": "Fitnow T-Shirt loja-teste - Feminino",
    "brand": "loja-teste",
    "categoriesIds": [
        "/104/72/",
        "/104/",
        "/104/267/"
    ],
    "gender": [
        "female"
    ],
    "age_group": [
        "adult"
    ],
    "Atributos Google": [
        "gender",
        "age_group"
    ],
    "items": [
        {
            "itemId": "24121",
            "name": "| PRETO - P",
            "nameComplete": "Fitnow T-Shirt loja-teste - Feminino | PRETO - P",
            "ean": "78993232323",
            "referenceId": [
                {
                    "Key": "RefId"
                }
            ],
            "Cor": [
                "Preto e Verde"
            ],
            "Tamanho": [
                "P"
            ],
            "variations": [
                "Cor",
                "Tamanho"
            ],
        },
    ]
  },
]

I can’t get him to read any of this JSON data, nor at least it seems to carry because when it rotates it appears only that something went wrong by my Scope.This is another problem that I’m having I’m not being able to know very well how to reference the lines of this JSON what is complicating me a lot.

Someone has some light for this problem?

1 answer

1


You need to send headers on your service $http:

$http({
    method: 'JSONP',
    url: API_URL,
    headers: {
        Content-Type: "application/json"
        // Você pode precisar da autorização também
        //Authorization: token  
    }
}).then(function ( success ){
    $scope.content = "Something went right";
},function ( error ){
    $scope.content = "Something went wrong";
});

Make sure that the server you request from has CORS configured (Access-Control-Allow-Origin: *, e. g.).

Browser other questions tagged

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