我在覆盆子PI中有一个Web应用程序和一个API. Web应用程序使用HTTP GET请求来显示其内容
现在,在web应用程序component.ts中:
export class AppComponent implements OnInit { results = {}; constructor(private http: HttpClient) {} ngOnInit(): void { var url = 'http://localhost:8000/api/'; var endpoint = 'test/'; this.http.get(url + endpoint).subscribe(data => { this.results = data['test']; }) } }
当我在覆盆子INSIDE上打开Web应用程序时,这种方法有效.
但是,当使用raspBerry的IP和应用程序正在运行的端口从其他设备打开Web应用程序时,我无法从API获取数据.
我认为这是因为’localhost’,并且一旦这个锉刀不能用STATIC IP设置我想要检索它的本地IP,做类似的东西:
ngOnInit(): void { var ip = <some code <-- HELP> var url = 'http://' + ip + ':8000/api/'; var endpoint = 'test/'; this.http.get(url + endpoint).subscribe(data => { this.results = data['test']; }) }
我已经测试过,如果我手动将IP放在代码中,虽然它只是用于测试,但我不想手动输入.
解决方法
您可以通过window.location.origin获取原点.有关详细信息,请查看
here
ngOnInit(): void { var ip = window.location.origin // this will give you the ip:port //if you just want the ip or hostname you can use window.location.hostname var url = ip + '/api/'; var endpoint = 'test/'; this.http.get(url + endpoint).subscribe(data => { this.results = data['test']; }) }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。