node.js - 来自客户端的 Angular 通用转发 IP,用于所有 SSR API 调用

标签 node.js angular angular-universal

我通过IP判断用户所在的城市,希望拼装后的页面指向具体的城市。如何将 IP 转发给 SSR 从后端发出的所有 api 请求?现在总是有 127.0.0.1

// All regular routes use the Universal engine
app.get('*', (req, res) => {
    res.render('index', { req });
});

我应该在此代码中更改什么,以便在 PHP 后端具有 x-ip header ,然后从 SSR 调用 API

最佳答案

你可以试试这个

  1. 你需要提供angular和客户端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 的请求中,例如使用如下所示的自定义 header (或将其添加到

注入(inject)器.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 以解析以从上面的自定义 header 中获取 IP

关于node.js - 来自客户端的 Angular 通用转发 IP,用于所有 SSR API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56361282/

相关文章:

javascript - 如何在较低级别的回调中使用变量?

javascript - 我们如何为不同的请求类型编写 Joi 模式?

angular - 单元测试将类动态添加到 HTML 按钮 Jasmine

javascript - Angular 通用意外 token { 在 npm run start :ssr 上

javascript - Mongoose 种群

node.js - 类型错误 : Cannot read property 'apply' of undefined in NodeJS using JEST unit testing

html - Ionic Angular ion-img 和后备图像问题

Angular 2 - 输入掩码 : Input box display formatted value, 而模型保留未格式化的值

Angular Universal 不适用于 Angular Google map

angular - 即使安装了 Yarn 也找不到模块 'yarn'