1

I want to get client ip Address in Angular 5 from http://freegeoip.net/json/?callback
I have a service

@Injectable()
export class JobService {
constructor(    
    private http: HttpClient) { }
    getIpAddress() {
            const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
            return this.http
              .get('http://freegeoip.net/json/?callback',
              { headers: headers })
              .map(response => response || {})
              .catch(this.handleError);
          }

      private handleError(error: HttpErrorResponse): Observable<any> {
         console.error('observable error: ', error);
         return Observable.throw(error);
      }
}

and call service in jobcomponent

export class JobsDetailComponent implements OnInit {
constructor(
    private jobService: JobService){}


ngOnInit(): void {
    console.log("ip");
    this.jobService.getIpAddress().subscribe(data => {
      console.log(data);
    });

}

when I am calling this service but it is not working as expected and showing error in the browser console.

Failed to load http://freegeoip.net/json/?callback: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access

How can i solve this issue ?

This url can work in ajax JavaScript , but in Angular doesn't work

$.getJSON('//freegeoip.net/json/?callback=?', function (data) {
       return JSON.stringify(data, null, 2);
     });
Mohammad Daliri
  • 1,370
  • 6
  • 20
  • 43

1 Answers1

7

It will work if you remove the { headers: headers } parameter.

VahidN
  • 18,457
  • 8
  • 73
  • 117
  • 1
    I have a working sample here: https://github.com/VahidN/angular-template-driven-forms-lab/tree/master/src/app/client-ip-address – VahidN Feb 27 '18 at 14:57
  • can you please help me to sovle this https://stackoverflow.com/questions/52241799/failed-to-compile-node-modules-macaddress-lib-windows-js-in-angular-5 @VahidN – Zhu Sep 09 '18 at 09:44
  • @VahidN Thanks for your Github.Your example helped me a lot – Mohammad Daliri Oct 08 '18 at 05:12