How do you configure i18next-express-middleware? - node.js

I am trying to get started using i18next with an Express server, but cannot get it working based on the examples in the docs.
My app consists of index.js (my Express server), package.json, and a locales directory with two translation files: en.json and es.json.
index.js
'use strict';
const express = require('express');
const i18n = require('i18next');
const i18nMiddleware = require('i18next-express-middleware');
const path = require('path');
const app = express();
const port = process.env.PORT || 8080;
i18n
.use(i18nMiddleware.LanguageDetector)
.init({
fallbackLng: 'en',
lowerCaseLng: true,
preload: ['en', 'es'],
resGetPath: path.join(__dirname, 'locales/__lng__.json'),
useCookie: false
});
app.use(i18nMiddleware.handle(i18n, {
removeLngFromUrl: false
}));
app.get('/', (req, res) => {
res.send(req.t('home.title'));
});
app.use(express.static(path.join(__dirname, 'public')));
module.exports = app.listen(port, (err) => {
if (err) {
console.log(err);
process.exit(1);
} else {
console.log(`Server is listening on port ${port}`);
}
});
package.json
{
"name": "i18n-server",
"version": "1.0.0",
"description": "Node Express server with i18next.",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "Shaun Scovil <sscovil#gmail.com>",
"license": "ISC",
"dependencies": {
"express": "4.15.2",
"i18next": "8.2.1",
"i18next-express-middleware": "1.0.5"
}
}
locales/en.json
{
"home": {
"title": "Hello World!"
}
}
locales/es.json
{
"home": {
"title": "Hola Mundo!"
}
}

Looks like a very old configuration...following the readme backend are moved to own plugins...your code should look something like:
var i18next = require('i18next');
var FsBackend = require('i18next-node-fs-backend');
var middleware = require('i18next-express-middleware');
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
i18next
.use(FsBackend)
.init({
lng: 'en',
saveMissing: true,
debug: true,
backend: {
loadPath: __dirname + '/locales/{{lng}}/{{ns}}.json',
addPath: __dirname + '/locales/{{lng}}/{{ns}}.missing.json'
},
nsSeparator: '#||#',
keySeparator: '#|#'
});
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(middleware.handle(i18next, {
// ignoreRoutes: ["/foo"],
// removeLngFromUrl: false
}));
as a sample you could have a look at https://github.com/i18next/i18nextify/blob/master/example/server.js
and for the filesystem check out https://github.com/i18next/i18next-node-fs-backend for details

Related

Node.js Data in the body not being saved

All my projects were working fine before but all of sudden the content of the body is not being saved as if the body is not being parsed or something. Just to check I created this simple project of book directory but no luck.
Any help would be appreciated.
Thank you
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var config = require('./config');
// import bodyParser from "body-parser";//for typscript code only, use require for js
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false }));
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var bookRouter = require('./routes/books_routes');
const url = config.mongoURL;
const connect = mongoose.connect(url);
connect.then((DB)=>{
console.log("Connected With the MongoDB Server");
},(err)=>{next(err)})
.catch((err)=>next(err));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({
extended: true
})); //Parse URL-encoded bodies
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/books',bookRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Route File
const express = require('express');
const mongoose =require('mongoose');
const Books = require('../models/books');
const bookrouter = express.Router();
// bookrouter.use(bodyparser.json());
bookrouter.use(express.json());
bookrouter.use(express.urlencoded({
extended: true
})); //Parse URL-encoded bodies
bookrouter.route('/')
.get((req,res,next)=>{
Books.find({})
.then((books)=>{
res.statusCode = 200;
res.setHeader('content-Type','application/json');
res.json(books);
},(err)=>{next(err)})
.catch((err)=>next(err))
})
.post((req,res,next)=>{
var book = new Books({
book_name: req.body.book_name,
book_author: req.body.book_author,
book_description: req.body.book_description
})
book.save()
.then((book)=>{
Books.findById(book._id)
.then((book)=>{
res.statusCode = 200;
res.setHeader('content-type','application/json');
res.json(book);
},(err)=>next(err))
})
})
.put((req,res,next)=>{
res.send("PUT request is not supported at this API");
})
.delete((req,res,next)=>{
Books.remove({})
.then((resp)=>{
res.statusCode=200;
res.setHeader('content-type','application/json');
res.send(resp);
})
})
module.exports = bookrouter;
Model file
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportlocalmongoose = require('passport-local-mongoose');
var Books = new Schema({
book_name :{
type:String
},
book_author:{
type:String
},
book_description:{
type:String
}
},{
timestamps:true
})
Books.plugin(passportlocalmongoose);
module.exports = mongoose.model('Book',Books);
package.json
{
"name": "books-directory",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "^1.19.0",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"mongodb": "^3.0.10",
"mongoose": "^5.1.7",
"mongoose-currency": "^0.2.0",
"morgan": "~1.9.1",
"passport": "^0.4.0",
"passport-local": "^1.0.0",
"passport-local-mongoose": "^5.0.1"
}
}

Cannot connect cluster mongo.db atlas

I'm currently trying to learn MEAN stack. The tutorial are about a task manager. Right now I'm trying to connect to mongodb atlas to retrieve sample data in database but they are not showing up http://localhost:3000/api/tasks
Here is my tasks.js file
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('drivers',['tasks']);
router.get('/tasks', function(req, res, next){
db.tasks.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
module.exports = router;
Here is my server.js file
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var task = require('./routes/tasks');
var app = express();
var port = 3000;
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/api', task);
app.listen(port, function(){
console.log('Server started on port' +port);
});
Here is my package.json file
{
"name": "mytasklist",
"version": "1.0.0",
"description": "Task Manager",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"ejs": "^2.6.1",
"express": "^4.17.1",
"mongojs": "^2.6.0"
}
}
Problem solved, I pasted the wrong version for my nodejs driver.
need to use mongojs version 3.0.0 to connect to atlas

Deploying MongoDB & Express based back-end API to Heroku dosen't work

I wrote a small front-end project with Vue.js, and Express was adopted in the back-end. The front-end and back-end were in two different directories respectively. The API works in my local environment but when I deploy my back-end api to Heroku, and tried GET request by Postman, it doesn't work.
In my index.js:
This is the listening port:
const port = process.env.PORT || 5000;
I am using mongoose to connect mLab:
const db = require("./config/keys").mongoURI;
mongoose.connect(db)
And my package.jsonis here:
{
"name": "backend-api",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node index.js",
"server": "nodemon index.js"
},
"author": "Yeoman_Li",
"license": "ISC",
"devDependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.4",
"mongoose": "^5.4.0"
}
}
My index.js is here:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
// CORS
app.all("*", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
res.header(
"Access-Control-Allow-Headers",
"Content-type, Accept, X-Access-Token, X-Key"
);
if ("OPTIONS" == req.method) res.status(200).end();
else next();
});
const mediaReq = require("./routes/api/mediaReq");
// DB
const db = require("./config/keys").mongoURI;
// body-parser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// connect to DB
mongoose
.connect(db)
.then(() => console.log("MonogoDB Connected"))
.catch(err => console.log(err));
// router
app.use("/api/mediaReq", mediaReq);
// port
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
And here is my api router:
const express = require("express");
const router = express.Router();
const mediaController = require("../../controllers/media");
// test
router.get("/test", (req, res) => {
res.json({ msg: "test works" });
});
// $route GET api/mediaReq/medias || /medias/:id
router.get("/medias", mediaController.allMedia);
router.get("/medias/:id", mediaController.byId);
router.post("/medias", mediaController.create);
router.delete("/medias/:id", mediaController.remove);
module.exports = router;
I used postman to send a simple GET request and it works:
http://localhost:5000/api/mediaReq/medias
But when I tried to send a GET request to my heroku backend-api, it doesn't work:
https://fast-reaches-23458.herokuapp.com/api/mediaReq/medias

Error with ports: vue.js+node.js project in heroku

Trying to deploy my fullstack project. Locally it builds and working well, but in Heroku, after 'git push heroku master' command and automatic build after it I get the application error - 503 Service Unavailable. It looks like there are different ports or maybe incorrect path to the root folder, where it is index.html
My vue.js config/index.js
'use strict'
const path = require('path')
module.exports = {
dev: {
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
port: 80,
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false,
useEslint: true,
showEslintErrorsInOverlay: false,
devtool: 'cheap-module-eval-source-map',
cacheBusting: true,
cssSourceMap: true
},
build: {
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
devtool: '#source-map',
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
bundleAnalyzerReport: process.env.npm_config_report
}
}
My package.json
...
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"postinstall": "nodemon app.js",
"start": "npm run build",
"unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
"e2e": "node test/e2e/runner.js",
"test": "npm run unit && npm run e2e",
"lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs",
"build": "node --optimize_for_size --max_old_space_size=2048 --gc_interval=100 build/build.js"
},
...
And the app.js, where I've defined 'dist' as a folder, where app should get main index.html - 'app.use(express.static('dist'))'
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const book = require('./api/routes/book');
const doingsRoutes = require('./api/routes/doings');
const targetsRoutes = require('./api/routes/targets');
const topsRoutes = require('./api/routes/tops');
const usersRoutes = require('./api/routes/users');
const app = express();
const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect(
'mongodb://nodejs-rest:' +
'nodejs-rest' +
'#nodejs-rest-shard-00-00-vwe6k.mongodb.net:27017,nodejs-rest-shard-00-01-vwe6k.mongodb.net:27017,nodejs-rest-shard-00-02-vwe6k.mongodb.net:27017/test?ssl=true&replicaSet=nodejs-rest-shard-0&authSource=admin',
{
promiseLibrary: require('bluebird')
}
);
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'false'}));
app.use('/api/doings', doingsRoutes);
app.use('/api/targets', targetsRoutes);
app.use('/api/tops', topsRoutes);
app.use('/api/users', usersRoutes);
app.use(function(req, res, next) {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.set("port", process.env.PORT || 80);
if (process.env.NODE_ENV === 'production') {
console.log('dist')
app.use(express.static('dist'));
}
app.listen(app.get("port"), () => {
console.log(`Find the server at: ${app.get("port")}`);
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.sendFile(path.join(__dirname, '../dist', 'index.html'));
});
app.set('view engine', 'html');
You need to add a server.js file with express and the entry route on the root foolder of you app (in the same folder where package.json/index.html is located) . I have a vue app on heroku as well, it's not very hard.
// server.js
const express = require('express')
const path = require('path')
const history = require('connect-history-api-fallback')
const app = express()
const staticFileMiddleware = express.static(path.join(__dirname + '/dist'))
app.use(staticFileMiddleware)
app.use(history({
disableDotRule: true,
verbose: true
}))
app.use(staticFileMiddleware)
app.get('/', function (req, res) {
res.render(path.join(__dirname + '/dist/index.html'))
})
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port
console.log('App now running on port', port)
})

nodejs fs printing view source code instead of rendering view on openshift

This app works fine locally and works on openshift with no errors, however the views aren't rendering it is just printing the source code. I tried deleting and recreating the app but still no luck.
Here is part of my server.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require("fs");
var handlebars = require("handlebars");
var WebPageTest = require('webpagetest');
// Web Page Test - API key.
var wpt = new WebPageTest('www.webpagetest.org', '1234567890');
var router = express.Router();
app.use("/css", express.static(__dirname + '/css'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/img", express.static(__dirname + '/img'));
/***** Views *****/
// Homepage.
app.get('/', function(req, res) {
var template = fs.readFileSync("views/index.html", "utf8");
// handlebars data, optional.
var source = {
message : "Homepage!"
};
var pageBuilder = handlebars.compile(template);
var pageText = pageBuilder(source);
res.writeHead(200, {"Context-Type": "text/html"});
res.write(pageText);
res.end();
});
/***** Start App *****/
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 5000;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
app.listen(server_port, server_ip_address, function(){
console.log("Listening on " + server_ip_address + ", server_port " + server_port);
});
Here is part of the package.json
{
"name": "wpt",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"body-parser": "^1.10.0",
"express": "^4.10.6",
"webpagetest": "^0.3.1",
"mongoose": "^3.8.21",
"handlebars": "^2.0.0",
"express3-handlebars": "^0.5.2",
"fs":"*"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
I added fs to the dependencies manually but it didn't seem to have any effect.
It's probably a lot easier to just use a handlebars Express views engine such as hbs. Example:
// ...
var hbs = require('hbs');
app.engine('hbs', hbs.__express);
app.engine('html', hbs.__express);
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
hbs.localsAsTemplateData(app);
app.get('/', function(req, res) {
res.render('index.html', {
message: 'Homepage!'
});
});
// ...

Resources