weixin_33726313 2018-01-14 07:59 采纳率: 0%
浏览 757

获取Angular 5中的IP地址

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);
     });
  • 写回答

1条回答 默认 最新

  • weixin_33691700 2018-01-14 09:41
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器