[Angular|Node.js] Jak uzyskać adres IP?
Aby w Angularze uzyskać adres IP klienta, utworzyć trzeba usługę w backendzie np. w Node.js, przez którą go pozyskamy.
Node.js i Express
Pierwsza rzecz to utworzenie projektu i zainstalowanie frameworka Express:
mkdir get-ip-server
cd ip-server
npm init -y
npm install express cors
W pliku server.js tworzymy zawartość:
const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors());
app.get('/api/ip', (req, res) => {
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
res.json({ ip });
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
I uruchamiamy nasz backend.
Angular
Teraz, gdy już masz działający backend, możesz pobierać adres IP w Angularze. Utwórzmy przykładową aplikację:
ng new show-ip
cd show-ip
Utwórz nowy serwis:
ng generate service ip
W pliku ip.service.ts utwórz kod pobierający adres IP:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class IpService {
private apiUrl = 'http://localhost:3000/api/ip';
constructor(private http: HttpClient) { }
getIp(): Observable<{ ip: string }> {
return this.http.get<{ ip: string }>(this.apiUrl);
}
}
Teraz zaktualizuj komponent app.component.ts:
import { Component, OnInit } from '@angular/core';
import { IpService } from './ip.service';
@Component({
selector: 'app-root',
template: `<h1>Twój adres IP: {{ ip }}</h1>`,
})
export class AppComponent implements OnInit {
ip: string | undefined;
constructor(private ipService: IpService) { }
ngOnInit() {
this.ipService.getIp().subscribe(data => {
this.ip = data.ip;
});
}
}
Zaimportuj HttpClientModule w app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
To wszystko, wejdź na http://localhost:4200 i sprawdź czy adres IP się wyświetla.
Komentarze
Prześlij komentarz
Dzięki za komentarz!