Skip to content

Instantly share code, notes, and snippets.

@sikanrong
Created April 26, 2020 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sikanrong/b9338fcc0430a56ff7d81edc17e38cfa to your computer and use it in GitHub Desktop.
Save sikanrong/b9338fcc0430a56ff7d81edc17e38cfa to your computer and use it in GitHub Desktop.
An Angular Universal interceptor which handles HTTP requests to relative routes to local files. Fixes prerender errors for Angular applications which do this.
import {Injectable, Inject, Optional} from '@angular/core';
import {
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpHeaders,
HttpResponse,
HttpErrorResponse
} from '@angular/common/http';
import {Request} from 'express';
import {REQUEST} from '@nguniversal/express-engine/tokens';
import {of, throwError} from "rxjs";
import {catchError} from "rxjs/operators";
import * as fs from "fs";
import * as path from "path";
import * as process from "process";
@Injectable()
export class UniversalInterceptor implements HttpInterceptor {
constructor(@Optional() @Inject(REQUEST) protected request: Request) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
let serverReq: HttpRequest<any> = req;
if (this.request) {
let newUrl = `${this.request.protocol}://${this.request.get('host')}`;
if (!req.url.startsWith('/')) {
newUrl += '/';
}
newUrl += req.url;
serverReq = req.clone({url: newUrl});
}
return next.handle(serverReq).pipe(
catchError((error: HttpErrorResponse) => {
console.error(`HTTP Request for ${req.url} failed, trying direct filesystem access.`);
try{
const filePath = path.join(process.cwd(), 'src', req.url);
let encoding = 'utf8';
if(req.responseType == 'arraybuffer'){
encoding = undefined;
}
let body = fs.readFileSync(filePath, encoding);
if(req.responseType == 'json'){
body = JSON.parse(body);
}
return of(new HttpResponse(
{ status: 200, body: body }
));
}catch(e){
return throwError(e);
}
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment