Lucas Phillip
Lucas Phillip

Reputation: 185

How to host an angular on Azure linux web app

I have this Angular app that I am trying to host using Linux web app on Azure. After deployment, I could not load the website so, after a little research, I found that I needed to add a index.js file (Cannot GET index.html Azure Linux Web App)

That fixed the fact that I could not load my website. But it does not fix angular routing issue. If I navigate to an angular route and hit refresh, the page does not get redirected to index.html and I get a 404 response. (See http://ecominas-website-qas.azurewebsites.net)

This is my index.js

var express = require('express');
var server = express();
var options = {
    index: 'index.html'
};
server.use('/', express.static('/home/site/wwwroot', options));
server.listen(process.env.PORT);

I have also tried adding a web.config as described here Hosting angular application in azure linux app service, but that would not load the index.html page and the default "everything is working but no app found" page was displayed.

How can I get angular routes working?

Thanks

Upvotes: 1

Views: 1059

Answers (1)

Lucas Phillip
Lucas Phillip

Reputation: 185

So, I have finally managed to get it working. After a few days of research and try/error, this is the index.js that worked for future reference

var express = require('express');
var path = require('path');

var server = express();
var options = {
    index: 'index.html',
    redirect: true,
};
server.use(express.static('/home/site/wwwroot', options));
const allowedExt = [
    '.js',
    '.ico',
    '.css',
    '.png',
    '.jpg',
    '.woff2',
    '.woff',
    '.ttf',
    '.svg',
  ];

server.get('*', (req, res) => {
    if (allowedExt.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
        res.sendFile(path.resolve(req.url));
    } else {
        res.sendFile(path.resolve('index.html'));
    }
});
server.listen(process.env.PORT);

Upvotes: 4

Related Questions