You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Node.js Express i18n时遇res未定义及语言切换失败问题

解决Express + EJS + i18n本地化的res未定义问题及硬编码切换语言方案

一、修复res未定义错误

i18n的init中间件会自动将本地化相关属性(如locale)和方法(如__)挂载到res.locals对象上,EJS模板默认可直接访问res.locals中的变量,无需通过res前缀调用。

修改index.ejs代码如下:

<!DOCTYPE html>
<html lang="<%= locale %>">

   <head>
      <meta charset="UTF-8">
      <title>Test App</title>
   </head>

   <body>
      <h1><%= __('test') %></h1>     
   </body>

</html>

二、实现硬编码切换语言

方式1:全局修改默认语言(重启生效)

直接修改i18n.configure的defaultLocale参数,即可全局切换默认语言:

i18n.configure({
    locales: ['en', 'fr'], 
    directory: __dirname + '/locales', 
    defaultLocale: 'fr', // 替换为'en'或'fr'切换全局默认语言
    cookie: 'lang',
});

方式2:路由内硬编码设置语言(动态生效)

在路由处理函数中调用req.setLocale(),强制设置当前请求的语言:
修改server.js,添加指定语言的路由:

const express = require('express');
const app = express();
const i18n = require('i18n');

i18n.configure({
    locales: ['en', 'fr'], 
    directory: __dirname + '/locales', 
    defaultLocale: 'en', 
    cookie: 'lang',
});

app.use(i18n.init);
app.set('view engine', 'ejs');

// 默认使用全局默认语言
app.get('/', (req, res) => {
    res.render('index');
});

// 硬编码切换为法语
app.get('/fr', (req, res) => {
    req.setLocale('fr');
    res.render('index');
});

// 硬编码切换为英语
app.get('/en', (req, res) => {
    req.setLocale('en');
    res.render('index');
});

app.listen(3000);

方式3:通过URL参数动态切换

通过URL参数传递语言标识,灵活设置当前请求语言:

app.get('/:lang?', (req, res) => {
    // 仅允许配置过的语言
    if (req.params.lang && ['en', 'fr'].includes(req.params.lang)) {
        req.setLocale(req.params.lang);
    }
    res.render('index');
});

访问http://localhost:3000/fr显示法语内容,http://localhost:3000/en显示英语内容,不指定参数则使用全局默认语言。

关键注意事项

  • 修正本地化JSON文件的格式错误:移除键值对后的尾随逗号,否则会导致JSON解析失败
    修正后的en.json:
    {
       "test": "this is a test"
    }
    
    修正后的fr.json:
    {
       "test": "c'est un test"
    }
    
  • i18n.init中间件必须在所有路由定义前挂载,确保本地化功能对所有请求生效

内容的提问来源于stack exchange,提问作者Dreamer64

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 17:55:55