i18n无法使用本地化网址

时间:2017-09-01 12:28:04

标签: node.js internationalization

我正在尝试将本地化添加到我的网站。我安装i18n,用西班牙语和英语创建2个本地化json文件,然后在app.js文件中添加配置。 app.js文件是这样的:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var i18n = require("i18n");
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var request = require('request');
var flash = require('express-flash');
var winston = require('winston');

winston.add(winston.transports.File, { name: 'app-info', maxFiles: 3, filename: 'logs/app-info.log', level: 'info' });
winston.add(winston.transports.File, { name: 'app-error', maxFiles: 3, filename: 'logs/app-error.log', level: 'error' });

require('dotenv').config();
var app_port   = process.env.APP_PORT;


var fs = require('fs');


var app = express();
app.listen(app_port, function(){
  console.log('listening on *:' + app_port);
});

// Include php notifications
var notifications = require('./phpmonitor');


// Define routes
var routes = require('./routes/index');
var login = require('./routes/login');
var doctors = require('./routes/doctors');
var new_appointment = require('./routes/new_appointment');
var new_appointment_medicine = require('./routes/new_appointment_medicine');
var new_appointment_psychology = require('./routes/new_appointment_psychology');
var appointments = require('./routes/appointments');
var videoconference = require('./routes/videoconference');
var user = require('./routes/user');
var user_doctor = require('./routes/user_doctor');
var doctor = require('./routes/doctor');
var history = require('./routes/history');
var public = require('./routes/public');
var ajax = require('./routes/ajax');
var patients = require('./routes/patients');


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// i18n setup
i18n.configure({
    locales:['es', 'en'],
    defaultLocale: 'es',
    objectNotation : true,
    queryParameter: 'lang',
    cookie: 'i18n',
    syncFiles: true,
    updateFiles: true,
    directory: __dirname + '/locales'
});

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());



app.use(i18n.init);
app.locals.request = request.defaults({jar: true});
app.locals.winston = winston;

// Set session
app.use(session({
  store: new RedisStore,
  secret: 'Y0V3NJS58jP61lfQjPn8gm99Cb2Ppl6y',
  resave: true,
  saveUninitialized: false,
}));

// Global use, set locale and basic locals
app.use(function(req, res, next) {

  var cookie = req.cookies.i18n;
  if (cookie === undefined) {
    res.cookie('i18n', 'es', { maxAge: 900000000, httpOnly: true });
  }

  // Wizard cookie
  var cookie_wizard = req.cookies.omnidoctor_wizard;
  if (cookie_wizard === undefined) {
    res.locals.wizard_cookies       = 'pending';
  }

  // Accept cookies
  var accept_cookies = req.cookies.omnidoctor_cookies;
  if (accept_cookies === undefined) {
    res.locals.accept_cookies       = 'pending';
  }

  i18n.setLocale(req, i18n.getLocale());
  app.locals.api            = process.env.API_URL;
  app.locals.site_url       = process.env.SITE_URL;
  app.locals.site_protocol  = process.env.SITE_PROTOCOL;
  app.locals.socket_port    = process.env.SOCKET_PORT;
  res.locals.analytics      = process.env.ANALYTICS;

  // Load moment with i18n locale
  app.locals.moment = require('moment');
  app.locals.moment.locale(i18n.getLocale());

  next();
});

app.use('/', routes);
app.use('/', login);
app.use('/doctors', doctors);
app.use('/history', history);
app.use('/new-appointment/medicine', new_appointment_medicine);
app.use(['/new-appointment/psychiatry', '/new-appointment/psychology'], new_appointment_psychology);
app.use('/new-appointment', new_appointment);
app.use('/appointments', appointments);
app.use('/videoconference', videoconference);
app.use('/', user);
app.use('/', user_doctor);
app.use('/', public);
app.use('/doctor', doctor);
app.use('/ajax', ajax);
app.use('/patients', patients);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

/*app.listen(3500, function () {
  console.log("express has started on port 3500");
});*/

module.exports = app;

我想在编写网址mywebsite.com/en或mywebsite.com/时使其正常工作,但它找不到它我试图遵循此文档:

https://www.npmjs.com/package/i18n

并查看不同的论坛,但没有一个解决方案适合我。缺少什么让它正常工作?我看到路线必须修改,但我也试过,但它没有用。

修改

我在网上看到的另一个教程之后改变了app.js文件。现在,当我访问mywebsite.com/时,它运行良好,但是当我访问mywebsite.com/es时,它并没有翻译它。

所以如果我在es.json文件翻译中有这个:

{
login:{
    title: "Bienvenido"
}
}

当我访问mywebsite.com/es时,会出现login.title

在router / index.js中我有这个:

router.get('/', requireLogin, function(req, res, next) {

  request = req.app.locals.request;

  res.setLocale(req.cookies.i18n);

  if( req.session.role == 'doctor' ) {

    var locals = {
        i18n: res
    };

    res.render('index', locals);
  }

});

router.get('/es', function (req, res) {
    res.cookie('i18n', 'es');
    res.redirect('/')
});

router.get('/en', function (req, res) {
    res.cookie('i18n', 'en');
    res.redirect('/')
});

1 个答案:

答案 0 :(得分:0)

你配置得很好所以我猜你的问题是在i18n库上使用,问题是你没有共享它。 我建议你去看看这个tuturial:

https://www.sitepoint.com/how-to-implement-internationalization-i18n-in-javascript

并确保以正确的方式使用lirary,例如,如果您要写标题,请使用它:

var headline = i18n.__('Main Headline');