I have started a new project with Angular Universal from the CLI. I would like to redirect the /api/** endpoints to a different server, but I am facing some issues.
I have seen the host is setup in the header of the requests, I change it in the following way:
// Example Express Rest API endpoints
server.get('/api/**', (req, res, next) => {
req.headers.host = 'http://localhost:3000'
next();
});
but I get the following error (the endpoint works, I have just copy/pasted the url I and I can get the results):
ERROR G [Error]: NG04002: 'localhost:3000/api/news'
at na.noMatchError (file:///Users/xxxxxx/Development/GitHub/xxxxxx/dist/xxxxxx/server/chunk-JY4VO6WS.mjs:2:39383)
at file:///Users/xxxxxx/Development/GitHub/xxxxxx/dist/xxxxxx/server/chunk-JY4VO6WS.mjs:2:40078
at file:///Users/xxxxxx/Development/GitHub/xxxxxx/dist/xxxxxx/server/chunk-RGNQT4QR.mjs:4:21085
later in the log I see
status: 200,
statusText: 'OK',
url: 'http://localhost:4000/api/news',
ok: false,
name: 'HttpErrorResponse',
message: 'Http failure during parsing for http://localhost:4000/api/news',
error: SyntaxError: Unexpected token < in JSON at position 0
as the URL has never been changed. In the Angular guide I have not seen any example, could you please suggest how to set the rewrite of the host?
Solution
In case someone else will get the same issue as me I post here the solution that works for me.
First thing, in the server.ts file this commented code I think it is for some static response, do not mangle here the req and res parameters as I have done, it does not have any effect if you want to send /api/** to another host:
I have installed http-proxy-middleware and configured in this way in server.ts
and it works, I will test better in other scenario and see if it is enough.