我通过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
最佳答案
你可以试试这个
- 你需要提供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)
)
- 然后,使用 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);
}
}
- 在您的应用模块中提供您的 http 拦截器
app.module.ts
import { HTTP_INTERCEPTORS } from ‘@angular/common/http’;
//...
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: IPHttpInterceptor, multi: true }
- 修改您的 API 以解析以从上面的自定义 header 中获取 IP
关于node.js - 来自客户端的 Angular 通用转发 IP,用于所有 SSR API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56361282/