Reputation: 740
I'm using the official i18n library to localize my Angular Universal app and am using a proxy to serve the localized versions.
My app works fine as long as there is a language present in the url (e.g: /en/page), but doesn't work otherwise (e.g: / or /page). I get the error Cannot GET /
whenever I try to access a page without the locale in the url.
How do I redirect the user to the localized version of the page using the accept-language
header of the request? If I try it with the code below, it creates a redirect loop and the page doesn't load.
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
function app() {
const server = express();
server.use(cookieParser());
server.use('/', (req, res, next) => {
const languages = ['en', 'de', 'fr'];
languages.forEach((locale) => {
const appServerModule = require(path.join(__dirname, locale, 'main.js'));
server.use(`/${locale}`, appServerModule.app(locale));
});
locale = (req.headers['accept-language'] || '').substring(0, 2);
if (!languages.includes(locale)) {
locale = 'en';
}
res.redirect(`/${locale}`)
});
return server;
}
function run() {
app().listen(4200, () => {
console.log(`Node Express server listening on http://localhost:4200`);
});
}
run();
Upvotes: 0
Views: 984
Reputation: 740
I managed to solve it like this:
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
function app() {
const server = express();
server.use(cookieParser());
const languages = ['en', 'de', 'fr'];
languages.forEach((locale) => {
const appServerModule = require(path.join(__dirname, locale, 'main.js'));
server.use(`/${locale}`, appServerModule.app(locale));
});
server.get('/(:locale(en|fr|de)/)?*', (req, res, next) => {
const { urlLocale } = req.params;
const userLocale = (req.headers['accept-language'] || '').substring(0, 2);
if (urlLocale !== userLocale) {
res.redirect(userLocale + req.url);
}
});
return server;
}
function run() {
app().listen(4200, () => {
console.log(`Node Express server listening on http://localhost:4200`);
});
}
run();
Upvotes: 2