i18n node.js setLocale无法正常工作!getLocale始终返回默认语言环境 [英] i18n node.js setLocale not working! getLocale ALWAYS returns the default locale

查看:89
本文介绍了i18n node.js setLocale无法正常工作!getLocale始终返回默认语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道即时通讯使用i18n库是否错误,但是我很确定即时通讯操作正确.

I dont know if im using i18n library wrong but I am pretty sure im doing it right.

我一直在尝试更改语言环境.这是我当前的代码.如您所见,我在glocal i81n变量上调用了setLocale,但它仍然打印出en

I have been trying to change the locale. Here is my current code. As you can see I call setLocale on the glocal i81n variable but it still prints out en

我试图做res.setLocale(req.args.lang);在我的控制器中,但仍会打印出默认的en语言.

I have tried to do res.setLocale(req.args.lang); in my controller BUT IT STILL PRINTS OUT the default language of en.

老实说,我不知道该库是否已损坏或我做错了什么.请帮忙!

I honestly don't know if this library is just broken or I'm doing this completely wrong. Please help!

/**
 * Main Express Application: set up express app
 */

'use strict';

// require third-party node modules
const express = require('express');
const sslRedirect = require('heroku-ssl-redirect');
const compression = require('compression');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const passport = require('passport');
const helmet = require('helmet');
const http = require('http');
const cors = require('cors'); // handle cors
const i18n = require('i18n'); // set up language

// env variables
const { NODE_ENV, COOKIE, REDIS_URL, REDIS_HOST, REDIS_PORT } = process.env;

// server
function server() {
  // require custom
  const models = require('./models'); // establish and grab db connection
  const cfgPassport = require('./services/passport'); // configuration for passport

  // require custom middleware
  const args = require('./middleware/args');
  const error = require('./middleware/error');
  const exit = require('./middleware/exit');
  const { attachJWTAuth } = require('./middleware/auth');

  // set up express app
  const app = express();
  const newServer = http.createServer(app);
  const io = require('socket.io')(newServer); // socket.io


  // set up redis with socket
  const redis = require('socket.io-redis');
  const socket = require('./services/socket'); // require socket service to initiate socket.io
  io.adapter(redis(REDIS_URL));

  // enable ssl redirect in production
  app.use(sslRedirect());

  // only log requests in development
  NODE_ENV === 'development' ? app.use(require('morgan')('dev')) : null;

  // add middleware and they must be in order
  app.use(compression()); // GZIP all assets
  app.use(cors()); // handle cors
  app.use(helmet()); // protect against vulnerabilities
  // app.use(rawBody); // adds rawBody to req object

  // set up language
  i18n.configure({
    locales: ['en', 'ko'], // set the languages here
    defaultLocale: 'en',
    queryParameter: 'lang', // query parameter to switch locale (ie. /home?lang=ch) - defaults to NULL
    cookie: COOKIE,
    directory: __dirname + '/locales'
  });

  // you will need to use cookieParser to expose cookies to req.cookies
  app.use(cookieParser());

  // i18n init parses req for language headers, cookies, etc.
  // NOTE: If user is logged in, locale is set in verifyJWTAuth method
  app.use(i18n.init);
  i18n.setLocale('ko');
  console.log(i18n.getLocale());

  // save raw body
  function rawBodySaver(req, res, buf, encoding) {
    if (buf && buf.length) req.rawBody = buf.toString(encoding || 'utf8');
  }

  // body parser
  app.use(bodyParser.json({ limit: '32mb', verify: rawBodySaver })); // raw application/json
  app.use(bodyParser.urlencoded({ limit: '32mb', verify: rawBodySaver, extended: false })); // application/x-www-form-urlencoded

  // NOTE: take this out because it interferes with multer
  // app.use(bodyParser.raw({ limit: '32mb', verify: rawBodySaver, type: () => true }));

  // only secure in production
  if (NODE_ENV === 'production') app.set('trust proxy', 1); // get ip address using req.ip

  // passport config, must be in this order!
  app.use(passport.initialize());
  cfgPassport(passport); // set up passport

  // custom middleware
  app.use(args.attach); // set req.args
  app.use(attachJWTAuth(passport));
  app.use(exit.middleware); // stops here if server is in the middle of shutting down

  // host public files
  // app.use(express.static(__dirname + '/public'));

  // set up routes
  const router = require('./routes')(passport); // grab routes
  app.use('/', router); // place routes here

  // error middleware MUST GO LAST
  app.use(error);

  // io connection, call socket.connect
  io.on('connection', socket.connect);

  return newServer; // return newServer
}

module.exports = server(); // return server app for testing

推荐答案

我是偶然发现的.

这确实应该在文档中,但我将其发布在这里,以便遇到此问题的其他可怜的人可以尝试一下.

This really should be in the documentation but I will post it here so that other poor souls who ran into this issue can try this out.

之所以无法正常工作,是因为我的.json文件带有逗号结尾.因此,它不是有效的.json文件.

The reason why nothing was working WAS BECAUSE my .json file had a trailing comma. Therefore it wasn't a valid .json file.

我花了两天时间才偶然发现了这一点.如果.json文件无效,则i18n应该在控制台中引发错误!!!

It took me two days to accidentally discover this. i18n SHOULD HAVE THROW AN ERROR in the console if the .json files are invalid!!!

无论如何,我删除了结尾的逗号,并且一切正常.

Anyways, I removed the trailing comma and everything just worked.

这篇关于i18n node.js setLocale无法正常工作!getLocale始终返回默认语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆