node.jsangularexpresshttp-redirectserver

NodeJS Express Host index.html File Then Route To Specific Spa Route with Params


I have an application that uses Angular 13 as the frontend and nodeJS with express for the backend. The backend servers the frontend files. I am working on adding subdomains into my application and although I somewhat got it to work, there are a couple issues I am running into that I can't quite find the solution too.

I have got most of it done but the issue seems to be that when I send the index.html with the sendFile() function, I manage to get the url changed to the Auth/Auth url with the parameters, but the website does not work and I get the following errors:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client This page isn’t working "domain" redirected you too many times.

I recently introduced subdomains and my server.js is:

const swagger = express();
var app = express();
//apiRoutes.use(enforce.HTTPS());
app.use(express.static(path.join(__dirname, '/dist/App'), { dotfiles: 'allow' }));

allRoutes.use(bodyParser.json({limit: '50mb'}));
allRoutes.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
allRoutes.use(cors());

// use JWT auth to secure the api
if (process.env.NODE_ENV !== "production" || process.env.ENV === "dev") {
    swagger.use('/', swaggerUi.serve, swaggerUi.setup(swaggerFile, { swaggerOptions: { persistAuthorization: true }}));
    app.use('/swagger', swaggerUi.serve, swaggerUi.setup(swaggerFile, { swaggerOptions: { persistAuthorization: true }}));
}
allRoutes.use('/webhooks', require('./backend/webhooks/webhooks.controller'));
allRoutes.use(subdomain('webhooks', require('./backend/webhooks/webhooks.controller')));

allRoutes.use('*', jwt());
// allRoutes.use(subdomain('api',  jwt()));
// api routes
allRoutes.use('/api/users', require('./backend/users/users.controller'));

// global error handler
// start server
app.use(subdomain('swagger', swagger));
// app.use(subdomain('webhooks', require('./backend/webhooks/webhooks.controller')));
app.use('/swagger', swagger);
app.get(/^\/(?!api).*/,async function(req,res) {
    let isNonExcludedUrl = !req.url.includes('swagger') && !req.subdomains.includes('swagger') &&!req.url.includes('webhooks') && !req.subdomains.includes('webhooks');
    console.log('subdomain ', req.subdomains);
    if(req.subdomains.includes('webhooks')) {
        console.log('in webhooks')
    } else if(req.subdomains.length > 0 && isNonExcludedUrl) {
        console.log('processing website subdomain ');
        await website.checkSubdomainForWebsite(req, res)
    } else if (isNonExcludedUrl) {  //&& !req.url.includes('webhooks')
        res.sendFile(path.join(__dirname + '/dist/App/index.html'));
    }
});
app.use('/', allRoutes);
allRoutes.use(errorHandler);
app.use(errorHandler);

const port = process.env.PORT ? (process.env.PORT) : 4000;
var server = http.createServer(options, app);

server.listen(port, () => {
    console.log("server starting on port : " + port)
});

The checkSubdomainForWebsite function is:


async function checkSubdomainForWebsite(req,res) {
    let orgIdent = req.subdomains[0];
   
    if (orgIdent) {
       let qrDevice = await getOrCreateWebsiteDevice(orgIdent);

        let websiteUrl =  `/Auth/Auth`;

        res.sendFile(path.join(__dirname+'/dist/DineNGo/index.html'));
        res.redirect(url.format({
            pathname: websiteUrl, // assuming that index.html lies on root route
            query: {
                "qr": encodeURIComponent(encrypt(orgIdent)),
                "website": true
            }
        }));
    }
}

The expected behavior is when the checkSubdomainForWebsite() function is called,, right after the res.sendFile() is called and the index.html is loaded, I want to route to a specific page of the Angular SPA with query params. The Angular specific component based url I want to navigate to is Auth/Auth.

Upon researching this, I found that both the res.sendFile() and res.redirect should not be used together and I am pretty sure that is what is causing the issue but I cannot find an alternate approach that works. What is the best way I can host the index.html file and route to a specific component in the angular frontend through routes. I have provided my service.js and other functions below. Please let me know if more information is needed and thanks for the help.


Solution

  • Yes, redirecting and sending file cannot be used together. So, you could send the file and then proceed with AJAX/Angular.

    You could try redirecting first with query string, but include some flag to the query string the handler will read on redirect, and by it know that now it needs to send the file (or maybe in memory variable, in combination with other checks), (this makes two requests, and wil trigger other middleware, and might cause too many redirects, so it would be better to handle it on frontend), for example:

    add flag to qs:

    "redirected": true
    

    read it every time:

    if(req.query.redirected) return res.sendFile(path.join(__dirname+'/dist/DineNGo/index.html'));
    

    code:

    async function checkSubdomainForWebsite(req,res) {
    
        let orgIdent = req.subdomains[0];
    
        // add some flag to make sure it's redirect in combination with other checks
        if(req.query.redirected) return res.sendFile(path.join(__dirname+'/dist/DineNGo/index.html'));
       
        if (orgIdent) {
           let qrDevice = await getOrCreateWebsiteDevice(orgIdent);
    
            let websiteUrl =  `/Auth/Auth`;
            // redirect first
            res.redirect(url.format({
                pathname: websiteUrl, // assuming that index.html lies on root route
                query: {
                    "qr": encodeURIComponent(encrypt(orgIdent)),
                    "website": true,
                    "redirected": true
                }
            }));
        }
    }