Mauritz Funke
Mauritz Funke

Reputation: 33

Why is Express redirecting infinitely redirecting me?

I am trying to setup a multi language website with Express and NodeJs. My problem is I get redirected what it feels like 100 times and my browser is giving me a error that the webpage is not working because it redirected me too many times.

app.js

app.use('/', (req,res,next) => {
  res.redirect('/en-US');
  next();
});

app.use('/:lang', indexRouter);
app.use('/:lang/users', usersRouter);

index.js (indexRouter)

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});

module.exports = router;

Upvotes: 0

Views: 1281

Answers (3)

jfriend00
jfriend00

Reputation: 707846

The problem is that this route handler:

app.use('/', (req,res,next) => {
  res.redirect('/en-US');
  next();
});

will get hit for not only /, but also /en-US. app.use() matches any route handler for which the path is equal to or a subset of the requested path. So, the browser requests "/", you redirect to "/en-US", which then redirects to "/en-US" and so on, an infinite loop.

I don't know the overall URL design of your site to know what the best overall solution is. You can prevent the infinite redirect loop by just changing app.use() to app.get():

app.get('/', (req,res,next) => {
  res.redirect('/en-US');
});

But, that will make the redirect only work for GET requests which may or may not be OK. If you want all HTTP verbs to redirect, you could change to app.all():

app.all('/', (req,res,next) => {
  res.redirect('/en-US');
});

The important thing to understand here is that app.get(), app.post(), app.all(), etc... all require an exact match for the URL path, whereas app.use() just requires a subset match. This is a little understood aspect of the Express design.


In addition, remove the call to next() after you do res.redirect(). At that point, you've sent the response, you don't want any other request handlers to see the request. You're done with routing.

Upvotes: 3

Eric Nderitu
Eric Nderitu

Reputation: 491

How about you try dealing with the '/' route through the app.js directly instead of index.js

Upvotes: 0

Eric Nderitu
Eric Nderitu

Reputation: 491

under your app.js

Try using

app.use('/', router )

Upvotes: 0

Related Questions