我通过IP确定用户所在的城市,并希望组合页面引用特定的城市。如何将IP转发到SSR从后端发出的所有api请求?现在总有127.0.0.1
userId
我应该对这段代码进行什么更改,以便在PHP后端具有x-ip标头,然后从SSR调用API
答案 0 :(得分:0)
您可以尝试类似
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)
)
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);
}
}
app.module.ts
import { HTTP_INTERCEPTORS } from ‘@angular/common/http’;
//...
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: IPHttpInterceptor, multi: true }