A
A
Alexander Florenko2019-10-13 14:33:57
Node.js
Alexander Florenko, 2019-10-13 14:33:57

How to make redirects in nodejs?

Hello.
I have a vue + ssr app
Actually ssr itself provides a node server.
On it I try to make the redirects I need.
The first one is a 301 redirect from a url with a slash to a url without a slash.
Tried to do so

const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
const stripTrailingSlash = url => url.replace(/\/$/, "");
const urlArray = fullUrl.split('');

res.setHeader("Content-Type", "text/html");
res.setHeader("Server", serverInfo);

if (urlArray[urlArray.length - 1] === '/') {
    res.writeHead(301, {'Location': stripTrailingSlash(fullUrl)});
    res.end();
}

But something is clearly not right here, when loading the page, first I see an empty page, and then the right one.
I also have application localization.
There are 2 locales, eg /en, /ru
I want to make it so that if there is no locale in the url, eg domain.com, then do a 301 redirect to domain.com/ru
I roughly understand how to write it, but if you do a redirect, then in the console it says that the number of redirects
has been exceeded

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question