How do you communicate from the browser with the express.js server using angular ssr?

115 Views Asked by At

I've run into an SSR issue that somehow neither the Angular docs nor the new Angular dev docs provide information about it or at least I did not find any.

I'd like to know how one transfers data from the browser to the server as the other way around is pretty easy using the TransferState API. It also seems kind of odd to me, that there isn't a TransferState analog for the other way or that the TransferState API isn't bidirectional.

I've tryed adding a post route in the server.ts in the app() function file like this:

server.post('/test', (req, res, next) => {
    console.log('The Body of the Request: ', req.body)
    res.send("Got the request!")
})

But whenever I try to call the route like this in the browser:

readonly #http = inject(HttpClient)

testEndpoint() {
    this.#http.post('http://localhost:4200/test', {hello: 'world'}).subscribe(console.log)
}

But when I try to call this in the browser like this:

if (isPlatformBrowser(this.platformID)) {
    this.#service.testEndpoint()
}

It returns an "NG04002" which basically means that the route couldn't be found by the RouterModule/Router. This doesn't make sense to me, but maybe I am missing something obvious.

Also do note that the code I provided is only pseudocode and may not be valid javascript/typescript code as I currently do not have access to my real code base. If this isn't suffient enought to pinpoint the error, please tell me, I'll add all of the stuff that is needed as long as this gets resolved.

2

There are 2 best solutions below

3
Naren Murali On

SSR is meant for prerendering the content on the server and hydrating (or not) on the client, it is not a web server for writing node.js code.

Because whatever routes you will hit, angular will search for the corresponding angular routing for that route!

Instead run a separate node.js server in port 4000 or anything except 4200 (default angular server port) and make api calls through this separate server!

0
SeamonDev On

I found the solution for my problem. Angular 17 apparently ignores the server.ts file when running ng serve and only take into account when you are building with ng build and executing the .mjs file afterwards. This is because angular uses an internal dev server and not the one you provided in server.ts.

https://github.com/angular/angular-cli/issues/26472 https://github.com/angular/angular-cli/issues/26323

These github issues were also made by confused people like me, but from what I got this is defined behavior. As far as I know this isn't documented anywhere inside the official angular documentation.