WarLion
WarLion

Reputation: 123

JSON API error with XMLHttpRequest

I'm trying to get some data from an API using JSON from a external API

The API URL is like this

http://60.62.62.62:8586/api/village/197571446817

And the data is this:

{
"userId": 197571446817,
"currentHomeId": 197571446817,
"clanId": 15489654523,
"clanName": "vlsn_nsmr",
"clanBadge": 1744850005,
"clanRole": "title",
"clanWar": 7,
"numberLogin": 0,
"secondsLogin": 0,
"league": "CRYSTAL_III",
"townHallLevel": 9,
"userName": "somename",
"level": 114,
"XP": 5516,
"gems": -234935969,
"freeGems": 0,
"attackRating": -721481846,
"attackKFactor": -1987233268,
"trophies": 1925,
"attackWinCount": 308,
"attackLoseCount": -1998035130,
"defenseWinCount": 3,
"defenseLoseCount": -840248882,
"nameChosenByUser": true,
"nameChanged": 0,
"villageImg": "",
"boughtGems": -1906210374
}

So far so good. But then I try to get some values using getJson:

$.getJSON('http://62.4.23.229:8338/api/village/197571446817', function(data) {
    console.log(data.userName)
}

And I get this:

XMLHttpRequest cannot load url No 'Access-Control-Allow-Origin' header is present on the requested resource Origin

I tried using jsonp but not luck seems this API doesn't like the callback. Does anyone know how I can get that info from that API?

Upvotes: 0

Views: 67

Answers (2)

Viraj Nalawade
Viraj Nalawade

Reputation: 3227

You are doing an XMLHttpRequest to a domain that is diffent that where your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons.
Possible solutions:-How can I achieve this by using CORS.
The simplest way to enable CORS is adding the necessary headers (as Access-Control-Allow-Origin) to the server's responses
I also advice to check if it just a typo in the target domain.

Upvotes: 1

DSA
DSA

Reputation: 780

The error message Access-Control-Allow-Origin says that API has security constraint in Header. You need to contact your api provider for more detail.

Upvotes: 1

Related Questions