来自客户端的所有SSR API调用的Angular Universal转发IP

时间:2019-05-29 12:59:52

标签: node.js angular angular-universal

我通过IP确定用户所在的城市,并希望组合页面引用特定的城市。如何将IP转发到SSR从后端发出的所有api请求?现在总有127.0.0.1

userId

我应该对这段代码进行什么更改,以便在PHP后端具有x-ip标头,然后从SSR调用API

1 个答案:

答案 0 :(得分:0)

您可以尝试类似

  1. 您需要为客户端IP提供角度

server.ts

import { REQUEST } from '@nguniversal/express-engine/tokens';

//..
app.engine('html', (_, options, callback) =>
  ngExpressEngine({
    bootstrap: AppServerModuleNgFactory,
    providers: [
      provideModuleMap(LAZY_MODULE_MAP),
      {
        provide: REQUEST,
        useValue: options.req, //Provides the request to angular
      },
    ],
  })(_, options, callback)
)
  1. 然后,使用HTTP Interceptor从http请求中获取IP地址,并将其添加到发送给API的请求中,例如使用如下所示的自定义标头(或将其添加

injector.ts

import { Injectable, Inject, Optional } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { REQUEST } from '@nguniversal/express-engine/tokens';


@Injectable()
export class IPHttpInterceptor implements HttpInterceptor {
  constructor(@Optional() @Inject(REQUEST) httpRequest: any) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const ip = httpRequest.connection.remoteAddress;

    if(ip) //ip wil be undefined client side
    {
        request = request.clone({
          setHeaders: {
            Client-IP: ip
          }
        });
    }
    return next.handle(request);
  }
}   
  1. 在应用模块中提供http拦截器

app.module.ts

import { HTTP_INTERCEPTORS } from ‘@angular/common/http’;
//...
 providers: [
 { provide: HTTP_INTERCEPTORS, useClass: IPHttpInterceptor, multi: true }
  1. 修改您的API进行解析,以从上面的自定义标头中获取IP