1

I am doing a service call in Angular and it is giving me error

XMLHttpRequest cannot load http://geo.groupkt.com/ip/172.217.3.14/json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access

When I see the Network Name , I found json and when I see details , I find the response

Request URL:http://geo.groupkt.com/ip/172.217.3.14/json
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:8888
Response Headers
view source
Age:1
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Encoding:gzip
Content-Length:232
Content-Type:application/json;charset=UTF-8
Date:Thu, 19 Jan 2017 14:51:51 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Vary:Accept-Encoding
Via:1.1 localhost.localdomain
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,hi;q=0.6,es;q=0.4
Host:geo.groupkt.com
Origin:http://localhost:3000
Proxy-Connection:keep-alive
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36

I have now doubt that even if the network says the call, CORS can be happen ? Why then it is saying like this, again when I debug the code I did not able to go into success.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
user2748108
  • 51
  • 2
  • 7
  • 1
    Possible duplicate of [How to create cross-domain request (Angular 2)?](http://stackoverflow.com/questions/34790051/how-to-create-cross-domain-request-angular-2) – eko Jan 19 '17 at 15:02
  • 1
    CORS is a browser/client feature - so even if your request is correctly resolved, your browsers blocks access to the resource because of cross-origin policy. Whoever the server `http://geo.groupkt.com/ip/172.217.3.14/json` is - it doesn't provide access to localhost:3000 making calls - the simplest solution is to use a proxy when you run your ng2 app - if you use the ng-cli : https://github.com/angular/angular-cli#proxy-to-backend – Ovidiu Dolha Jan 19 '17 at 15:05

1 Answers1

0

CORS is protection against making your JavaScript calls to external servers (due to XSS for example). To give your app privilege to connect to your server it need to respond with some headers:

Access-Control-Allow-Origin: yourHost.com   <the most important one>
Access-Control-Allow-Methods: POST, GET, OPTIONS <list of methods which you want to perform>
Access-Control-Allow-Headers: authorization, content-type
Access-Control-Allow-Credentials: true

more about headers: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers section CORS

You can read more here:

https://www.w3.org/TR/cors https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Maciej Treder
  • 11,866
  • 5
  • 51
  • 74