Angular, is there a way to return a HTTP status code different than 200, but only after the API call response?

The main goal is to return an HTTP status code different than 200, but only after the API call response, which will notify us if the page is found or not found.

From what I’ve read, there is no way to accomplish this except using an SSR, which acts as a server and can set a status code.


If there is another way to do this we can skip the SSR part.

I need help to integrate the SSR into the NOT fresh install Angular 8 Project.
I have compiled the SSR code and have also set the express server running.



The problems I have are the following:


  1. The express server parses only the main request (the one from the browser URL bar) but the API calls made from Angular are not passing through the express server. I’m using the HttpClient wrapped in service for better usage.
Therefore I cannot check what status code the API call is returning and then set it as a page response. This affects the SEO of the website and all pages (found or not found) are marked with status 200.


  2. The window object is missing when express js server is serving the content. This is expected but I need the window and document objects because we have some jQuery libraries running along with Angular. 


  3. The app stopped acting like an Angular app and per every link click the page gets reloaded


  4. What is the correct way to set the express server to serve the content to the Apache server which is handling the domain. Proxy or maybe some other service?

Answer

You can try to use a simple express server without the SSR. Then just simply serve the compiled application through the express server and make the initial call to the API through the express server. After that you can set the status code before the Angular is loaded

"use strict";
 const express = require("express"); 
 const compression = require("compression");

 const nodeFetch = require("node-fetch");

 const _port = 4100;
 const _app_folder = 'dist/browser';

 const app = express();

 app.use(compression());

 // ---- SERVE STATIC FILES ---- //
 app.get('*.*', express.static(_app_folder, {maxAge: '1y'}));

 // ---- SERVE APLICATION PATHS ---- //
 app.all('*', function (req, res) {

    let url = 'http://example.com' + req.url;

    nodeFetch(url).then(apiRes => {


       if(apiRes.status == 404){
          res.status(404).sendFile(`/`, {root: _app_folder});
       }  else {
          res.status(200).sendFile(`/`, {root: _app_folder});
       }

     })

  });

 // ---- START UP THE NODE SERVER  ----
 app.listen(_port, function () {
   console.log("Node Express server for " + app.name + " listening on  
   http://localhost:" + _port);
 });