NuxtJs serverMiddleware causing error on production
The NuxtJs app running well with npm run dev
but npm run build
causing the following error
Here is my server/index.js
require('dotenv').config()
const express = require('express')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const api = require('./api')
const socket = require('./socket')
const host = process.env.HOST
const port = process.env.PORT
app.set('port', port)
// Listen the server
const server = app.listen(port, host)
const io = require('socket.io').listen(server)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
console.log('Server listening on http://' + host + ':' + port) // eslint-disable-line no-console
}
start()
// Online users list by country
app.locals.onlineUsers = {};
// Users who is searching partners
app.locals.searchingUsers = {}
socket.start(io, app)
app.use('/api', api)
module.exports = app
And here is my nuxt.config.js
require('dotenv').config()
const pkg = require('./package')
module.exports = {
mode: 'universal',
debug: true,
serverMiddleware: [
{ path: '/api', handler: '~/server/index.js' }
],
/*
** Headers of the page
*/
head: {
title: pkg.name,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: 'http://chateg.com/favicon.ico' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Fredoka+One|Montserrat:200,400,500,700,800&subset=cyrillic' }
]
},
/*
** Customize the progress-bar color
*/
loading: false,
/*
** Global CSS
*/
css: [
'@/assets/scss/main.scss'
],
/*
** Router middlewares
*/
router: {
middleware: 'i18n'
},
/*
** Plugins to load before mounting the App
*/
plugins: [
{ src: '~/plugins/i18n.js', ssr: true },
{ src: '~/plugins/vue-select.js', ssr: false },
{ src: '~/plugins/vue-flux.js', ssr: false },
{ src: '~plugins/ga.js', ssr: false },
{ src: '~plugins/socket.io.js', ssr: false }
],
/*
** Generate dynamic routes
*/
generate: {
routes: [
'/ru/login',
'/uz/login',
'/ru/chat',
'/uz/chat'
]
},
/*
** Nuxt.js modules
*/
modules: [
'@nuxtjs/axios',
'@nuxtjs/router',
'@nuxtjs/sitemap',
['@nuxtjs/component-cache', {
max: 10000,
maxAge: 1000 * 60 * 60
}],
['@nuxtjs/google-analytics', {
id: 'UA-129371850-1'
}]
],
/*
** Generates sitemap
*/
sitemap: {
path: '/sitemap.xml',
hostname: 'http://chateg.com',
cacheTime: 1000 * 60 * 15,
gzip: true,
generate: false, // Enable me when using nuxt generate
exclude: [
'/secret',
'/admin/**'
],
routes: [
'/ru/login',
'/uz/login',
'/ru/chat',
'/uz/chat'
]
},
/*
** Axios module configuration
*/
axios: {
baseURL: process.env.BASE_URL
},
/*
** Build configuration
*/
build: {
// analyze: true,
/*
** You can extend webpack config here
*/
extend(config, ctx) {
// config.resolve.alias['vue'] = 'vue/dist/vue.common'
// Run ESLint on save
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
Here is my server/api/index.js
const express = require('express')
const router = express.Router()
const request = require('request')
const getPostData = require('../middleware/getPostData')
const help = require('../helper')
router.use(getPostData)
router.post('/login', function (req, res) {
let user = null;
if (req.body.user) {
user = req.body.user;
console.log(user)
}
if (!user.sex || !user.partner || !user.country || !user.token) {
return res.status(400).json({ message: "Something went wrong!" });
}
const verifyCaptchaOptions = {
uri: "https://www.google.com/recaptcha/api/siteverify",
json: true,
form: {
secret: '6Ld4RnQUAAAAAPdZaBbHdginQWteAohILLt1OXuT',
response: user.token
}
}
request.post(verifyCaptchaOptions, function (err, response, body) {
if (err) {
return res.status(500).json({ message: "oops, something went wrong on our side" });
}
if (!body.success) {
return res.status(500).json({ message: body["error-codes"].join(".") });
}
//Save the user to the database. At this point they have been verified.
res.status(201).json({ success: true, user: user });
});
})
router.get('/get_users', function (req, res) {
let numberOfOnlineUsers = 0;
let users = req.app.locals.onlineUsers;
if (Object.keys(users).length) {
for (const key in users) {
if (users.hasOwnProperty(key)) {
numberOfOnlineUsers += help.countArray(users[key]);
}
}
}
res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})
router.get('/get_users_from_country', function (req, res) {
let numberOfOnlineUsers = 0;
let countryId = 'undefined';
let users = req.app.locals.onlineUsers;
if (req.query.countryId) {
countryId = req.query.countryId;
}
if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
numberOfOnlineUsers = help.countArray(users[countryId]);
}
res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})
router.get('/get_males_and_females', function (req, res) {
let males = 0;
let females = 0;
let countryId = 'undefined';
let users = req.app.locals.onlineUsers;
if (req.query.countryId) {
countryId = req.query.countryId;
}
if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
users[countryId].forEach(item => {
if (item.sex == 'female') {
females++;
} else if (item.sex == 'male') {
males++;
}
})
}
res.status(201).json({ males: males, females: females })
})
module.exports = router
I am sure the bug related to serverMiddleware
of nuxt in the config cause when I commented it it is working good but I can't access my API.
Please help me as much as possible. I have not been able to solve this problem for 2 days.
express vue.js nuxt.js
add a comment |
The NuxtJs app running well with npm run dev
but npm run build
causing the following error
Here is my server/index.js
require('dotenv').config()
const express = require('express')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const api = require('./api')
const socket = require('./socket')
const host = process.env.HOST
const port = process.env.PORT
app.set('port', port)
// Listen the server
const server = app.listen(port, host)
const io = require('socket.io').listen(server)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
console.log('Server listening on http://' + host + ':' + port) // eslint-disable-line no-console
}
start()
// Online users list by country
app.locals.onlineUsers = {};
// Users who is searching partners
app.locals.searchingUsers = {}
socket.start(io, app)
app.use('/api', api)
module.exports = app
And here is my nuxt.config.js
require('dotenv').config()
const pkg = require('./package')
module.exports = {
mode: 'universal',
debug: true,
serverMiddleware: [
{ path: '/api', handler: '~/server/index.js' }
],
/*
** Headers of the page
*/
head: {
title: pkg.name,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: 'http://chateg.com/favicon.ico' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Fredoka+One|Montserrat:200,400,500,700,800&subset=cyrillic' }
]
},
/*
** Customize the progress-bar color
*/
loading: false,
/*
** Global CSS
*/
css: [
'@/assets/scss/main.scss'
],
/*
** Router middlewares
*/
router: {
middleware: 'i18n'
},
/*
** Plugins to load before mounting the App
*/
plugins: [
{ src: '~/plugins/i18n.js', ssr: true },
{ src: '~/plugins/vue-select.js', ssr: false },
{ src: '~/plugins/vue-flux.js', ssr: false },
{ src: '~plugins/ga.js', ssr: false },
{ src: '~plugins/socket.io.js', ssr: false }
],
/*
** Generate dynamic routes
*/
generate: {
routes: [
'/ru/login',
'/uz/login',
'/ru/chat',
'/uz/chat'
]
},
/*
** Nuxt.js modules
*/
modules: [
'@nuxtjs/axios',
'@nuxtjs/router',
'@nuxtjs/sitemap',
['@nuxtjs/component-cache', {
max: 10000,
maxAge: 1000 * 60 * 60
}],
['@nuxtjs/google-analytics', {
id: 'UA-129371850-1'
}]
],
/*
** Generates sitemap
*/
sitemap: {
path: '/sitemap.xml',
hostname: 'http://chateg.com',
cacheTime: 1000 * 60 * 15,
gzip: true,
generate: false, // Enable me when using nuxt generate
exclude: [
'/secret',
'/admin/**'
],
routes: [
'/ru/login',
'/uz/login',
'/ru/chat',
'/uz/chat'
]
},
/*
** Axios module configuration
*/
axios: {
baseURL: process.env.BASE_URL
},
/*
** Build configuration
*/
build: {
// analyze: true,
/*
** You can extend webpack config here
*/
extend(config, ctx) {
// config.resolve.alias['vue'] = 'vue/dist/vue.common'
// Run ESLint on save
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
Here is my server/api/index.js
const express = require('express')
const router = express.Router()
const request = require('request')
const getPostData = require('../middleware/getPostData')
const help = require('../helper')
router.use(getPostData)
router.post('/login', function (req, res) {
let user = null;
if (req.body.user) {
user = req.body.user;
console.log(user)
}
if (!user.sex || !user.partner || !user.country || !user.token) {
return res.status(400).json({ message: "Something went wrong!" });
}
const verifyCaptchaOptions = {
uri: "https://www.google.com/recaptcha/api/siteverify",
json: true,
form: {
secret: '6Ld4RnQUAAAAAPdZaBbHdginQWteAohILLt1OXuT',
response: user.token
}
}
request.post(verifyCaptchaOptions, function (err, response, body) {
if (err) {
return res.status(500).json({ message: "oops, something went wrong on our side" });
}
if (!body.success) {
return res.status(500).json({ message: body["error-codes"].join(".") });
}
//Save the user to the database. At this point they have been verified.
res.status(201).json({ success: true, user: user });
});
})
router.get('/get_users', function (req, res) {
let numberOfOnlineUsers = 0;
let users = req.app.locals.onlineUsers;
if (Object.keys(users).length) {
for (const key in users) {
if (users.hasOwnProperty(key)) {
numberOfOnlineUsers += help.countArray(users[key]);
}
}
}
res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})
router.get('/get_users_from_country', function (req, res) {
let numberOfOnlineUsers = 0;
let countryId = 'undefined';
let users = req.app.locals.onlineUsers;
if (req.query.countryId) {
countryId = req.query.countryId;
}
if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
numberOfOnlineUsers = help.countArray(users[countryId]);
}
res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})
router.get('/get_males_and_females', function (req, res) {
let males = 0;
let females = 0;
let countryId = 'undefined';
let users = req.app.locals.onlineUsers;
if (req.query.countryId) {
countryId = req.query.countryId;
}
if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
users[countryId].forEach(item => {
if (item.sex == 'female') {
females++;
} else if (item.sex == 'male') {
males++;
}
})
}
res.status(201).json({ males: males, females: females })
})
module.exports = router
I am sure the bug related to serverMiddleware
of nuxt in the config cause when I commented it it is working good but I can't access my API.
Please help me as much as possible. I have not been able to solve this problem for 2 days.
express vue.js nuxt.js
I have a serverMiddleware but I don't import it into server/index.js. I have it in api/test.js and export it withmodule.exports = {path: "/api/test", handler: app}
then in nuxt.config.jsserverMiddleware: ['~/api/test'],
. This works but I haven't run build yet.
– Andrew1325
Nov 21 '18 at 8:50
I also tried that. But it did not helped me cause it is programmatically same
– G'ofur N
Nov 21 '18 at 8:54
maybe need to show us your api code
– Andrew1325
Nov 21 '18 at 8:58
I updated the question
– G'ofur N
Nov 21 '18 at 9:04
I am not sure but Socket.io might be causing the bug?
– G'ofur N
Nov 21 '18 at 9:04
add a comment |
The NuxtJs app running well with npm run dev
but npm run build
causing the following error
Here is my server/index.js
require('dotenv').config()
const express = require('express')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const api = require('./api')
const socket = require('./socket')
const host = process.env.HOST
const port = process.env.PORT
app.set('port', port)
// Listen the server
const server = app.listen(port, host)
const io = require('socket.io').listen(server)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
console.log('Server listening on http://' + host + ':' + port) // eslint-disable-line no-console
}
start()
// Online users list by country
app.locals.onlineUsers = {};
// Users who is searching partners
app.locals.searchingUsers = {}
socket.start(io, app)
app.use('/api', api)
module.exports = app
And here is my nuxt.config.js
require('dotenv').config()
const pkg = require('./package')
module.exports = {
mode: 'universal',
debug: true,
serverMiddleware: [
{ path: '/api', handler: '~/server/index.js' }
],
/*
** Headers of the page
*/
head: {
title: pkg.name,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: 'http://chateg.com/favicon.ico' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Fredoka+One|Montserrat:200,400,500,700,800&subset=cyrillic' }
]
},
/*
** Customize the progress-bar color
*/
loading: false,
/*
** Global CSS
*/
css: [
'@/assets/scss/main.scss'
],
/*
** Router middlewares
*/
router: {
middleware: 'i18n'
},
/*
** Plugins to load before mounting the App
*/
plugins: [
{ src: '~/plugins/i18n.js', ssr: true },
{ src: '~/plugins/vue-select.js', ssr: false },
{ src: '~/plugins/vue-flux.js', ssr: false },
{ src: '~plugins/ga.js', ssr: false },
{ src: '~plugins/socket.io.js', ssr: false }
],
/*
** Generate dynamic routes
*/
generate: {
routes: [
'/ru/login',
'/uz/login',
'/ru/chat',
'/uz/chat'
]
},
/*
** Nuxt.js modules
*/
modules: [
'@nuxtjs/axios',
'@nuxtjs/router',
'@nuxtjs/sitemap',
['@nuxtjs/component-cache', {
max: 10000,
maxAge: 1000 * 60 * 60
}],
['@nuxtjs/google-analytics', {
id: 'UA-129371850-1'
}]
],
/*
** Generates sitemap
*/
sitemap: {
path: '/sitemap.xml',
hostname: 'http://chateg.com',
cacheTime: 1000 * 60 * 15,
gzip: true,
generate: false, // Enable me when using nuxt generate
exclude: [
'/secret',
'/admin/**'
],
routes: [
'/ru/login',
'/uz/login',
'/ru/chat',
'/uz/chat'
]
},
/*
** Axios module configuration
*/
axios: {
baseURL: process.env.BASE_URL
},
/*
** Build configuration
*/
build: {
// analyze: true,
/*
** You can extend webpack config here
*/
extend(config, ctx) {
// config.resolve.alias['vue'] = 'vue/dist/vue.common'
// Run ESLint on save
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
Here is my server/api/index.js
const express = require('express')
const router = express.Router()
const request = require('request')
const getPostData = require('../middleware/getPostData')
const help = require('../helper')
router.use(getPostData)
router.post('/login', function (req, res) {
let user = null;
if (req.body.user) {
user = req.body.user;
console.log(user)
}
if (!user.sex || !user.partner || !user.country || !user.token) {
return res.status(400).json({ message: "Something went wrong!" });
}
const verifyCaptchaOptions = {
uri: "https://www.google.com/recaptcha/api/siteverify",
json: true,
form: {
secret: '6Ld4RnQUAAAAAPdZaBbHdginQWteAohILLt1OXuT',
response: user.token
}
}
request.post(verifyCaptchaOptions, function (err, response, body) {
if (err) {
return res.status(500).json({ message: "oops, something went wrong on our side" });
}
if (!body.success) {
return res.status(500).json({ message: body["error-codes"].join(".") });
}
//Save the user to the database. At this point they have been verified.
res.status(201).json({ success: true, user: user });
});
})
router.get('/get_users', function (req, res) {
let numberOfOnlineUsers = 0;
let users = req.app.locals.onlineUsers;
if (Object.keys(users).length) {
for (const key in users) {
if (users.hasOwnProperty(key)) {
numberOfOnlineUsers += help.countArray(users[key]);
}
}
}
res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})
router.get('/get_users_from_country', function (req, res) {
let numberOfOnlineUsers = 0;
let countryId = 'undefined';
let users = req.app.locals.onlineUsers;
if (req.query.countryId) {
countryId = req.query.countryId;
}
if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
numberOfOnlineUsers = help.countArray(users[countryId]);
}
res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})
router.get('/get_males_and_females', function (req, res) {
let males = 0;
let females = 0;
let countryId = 'undefined';
let users = req.app.locals.onlineUsers;
if (req.query.countryId) {
countryId = req.query.countryId;
}
if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
users[countryId].forEach(item => {
if (item.sex == 'female') {
females++;
} else if (item.sex == 'male') {
males++;
}
})
}
res.status(201).json({ males: males, females: females })
})
module.exports = router
I am sure the bug related to serverMiddleware
of nuxt in the config cause when I commented it it is working good but I can't access my API.
Please help me as much as possible. I have not been able to solve this problem for 2 days.
express vue.js nuxt.js
The NuxtJs app running well with npm run dev
but npm run build
causing the following error
Here is my server/index.js
require('dotenv').config()
const express = require('express')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const api = require('./api')
const socket = require('./socket')
const host = process.env.HOST
const port = process.env.PORT
app.set('port', port)
// Listen the server
const server = app.listen(port, host)
const io = require('socket.io').listen(server)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
console.log('Server listening on http://' + host + ':' + port) // eslint-disable-line no-console
}
start()
// Online users list by country
app.locals.onlineUsers = {};
// Users who is searching partners
app.locals.searchingUsers = {}
socket.start(io, app)
app.use('/api', api)
module.exports = app
And here is my nuxt.config.js
require('dotenv').config()
const pkg = require('./package')
module.exports = {
mode: 'universal',
debug: true,
serverMiddleware: [
{ path: '/api', handler: '~/server/index.js' }
],
/*
** Headers of the page
*/
head: {
title: pkg.name,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: 'http://chateg.com/favicon.ico' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Fredoka+One|Montserrat:200,400,500,700,800&subset=cyrillic' }
]
},
/*
** Customize the progress-bar color
*/
loading: false,
/*
** Global CSS
*/
css: [
'@/assets/scss/main.scss'
],
/*
** Router middlewares
*/
router: {
middleware: 'i18n'
},
/*
** Plugins to load before mounting the App
*/
plugins: [
{ src: '~/plugins/i18n.js', ssr: true },
{ src: '~/plugins/vue-select.js', ssr: false },
{ src: '~/plugins/vue-flux.js', ssr: false },
{ src: '~plugins/ga.js', ssr: false },
{ src: '~plugins/socket.io.js', ssr: false }
],
/*
** Generate dynamic routes
*/
generate: {
routes: [
'/ru/login',
'/uz/login',
'/ru/chat',
'/uz/chat'
]
},
/*
** Nuxt.js modules
*/
modules: [
'@nuxtjs/axios',
'@nuxtjs/router',
'@nuxtjs/sitemap',
['@nuxtjs/component-cache', {
max: 10000,
maxAge: 1000 * 60 * 60
}],
['@nuxtjs/google-analytics', {
id: 'UA-129371850-1'
}]
],
/*
** Generates sitemap
*/
sitemap: {
path: '/sitemap.xml',
hostname: 'http://chateg.com',
cacheTime: 1000 * 60 * 15,
gzip: true,
generate: false, // Enable me when using nuxt generate
exclude: [
'/secret',
'/admin/**'
],
routes: [
'/ru/login',
'/uz/login',
'/ru/chat',
'/uz/chat'
]
},
/*
** Axios module configuration
*/
axios: {
baseURL: process.env.BASE_URL
},
/*
** Build configuration
*/
build: {
// analyze: true,
/*
** You can extend webpack config here
*/
extend(config, ctx) {
// config.resolve.alias['vue'] = 'vue/dist/vue.common'
// Run ESLint on save
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
Here is my server/api/index.js
const express = require('express')
const router = express.Router()
const request = require('request')
const getPostData = require('../middleware/getPostData')
const help = require('../helper')
router.use(getPostData)
router.post('/login', function (req, res) {
let user = null;
if (req.body.user) {
user = req.body.user;
console.log(user)
}
if (!user.sex || !user.partner || !user.country || !user.token) {
return res.status(400).json({ message: "Something went wrong!" });
}
const verifyCaptchaOptions = {
uri: "https://www.google.com/recaptcha/api/siteverify",
json: true,
form: {
secret: '6Ld4RnQUAAAAAPdZaBbHdginQWteAohILLt1OXuT',
response: user.token
}
}
request.post(verifyCaptchaOptions, function (err, response, body) {
if (err) {
return res.status(500).json({ message: "oops, something went wrong on our side" });
}
if (!body.success) {
return res.status(500).json({ message: body["error-codes"].join(".") });
}
//Save the user to the database. At this point they have been verified.
res.status(201).json({ success: true, user: user });
});
})
router.get('/get_users', function (req, res) {
let numberOfOnlineUsers = 0;
let users = req.app.locals.onlineUsers;
if (Object.keys(users).length) {
for (const key in users) {
if (users.hasOwnProperty(key)) {
numberOfOnlineUsers += help.countArray(users[key]);
}
}
}
res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})
router.get('/get_users_from_country', function (req, res) {
let numberOfOnlineUsers = 0;
let countryId = 'undefined';
let users = req.app.locals.onlineUsers;
if (req.query.countryId) {
countryId = req.query.countryId;
}
if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
numberOfOnlineUsers = help.countArray(users[countryId]);
}
res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})
router.get('/get_males_and_females', function (req, res) {
let males = 0;
let females = 0;
let countryId = 'undefined';
let users = req.app.locals.onlineUsers;
if (req.query.countryId) {
countryId = req.query.countryId;
}
if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
users[countryId].forEach(item => {
if (item.sex == 'female') {
females++;
} else if (item.sex == 'male') {
males++;
}
})
}
res.status(201).json({ males: males, females: females })
})
module.exports = router
I am sure the bug related to serverMiddleware
of nuxt in the config cause when I commented it it is working good but I can't access my API.
Please help me as much as possible. I have not been able to solve this problem for 2 days.
express vue.js nuxt.js
express vue.js nuxt.js
edited Nov 21 '18 at 9:04
G'ofur N
asked Nov 21 '18 at 7:55
G'ofur NG'ofur N
10112
10112
I have a serverMiddleware but I don't import it into server/index.js. I have it in api/test.js and export it withmodule.exports = {path: "/api/test", handler: app}
then in nuxt.config.jsserverMiddleware: ['~/api/test'],
. This works but I haven't run build yet.
– Andrew1325
Nov 21 '18 at 8:50
I also tried that. But it did not helped me cause it is programmatically same
– G'ofur N
Nov 21 '18 at 8:54
maybe need to show us your api code
– Andrew1325
Nov 21 '18 at 8:58
I updated the question
– G'ofur N
Nov 21 '18 at 9:04
I am not sure but Socket.io might be causing the bug?
– G'ofur N
Nov 21 '18 at 9:04
add a comment |
I have a serverMiddleware but I don't import it into server/index.js. I have it in api/test.js and export it withmodule.exports = {path: "/api/test", handler: app}
then in nuxt.config.jsserverMiddleware: ['~/api/test'],
. This works but I haven't run build yet.
– Andrew1325
Nov 21 '18 at 8:50
I also tried that. But it did not helped me cause it is programmatically same
– G'ofur N
Nov 21 '18 at 8:54
maybe need to show us your api code
– Andrew1325
Nov 21 '18 at 8:58
I updated the question
– G'ofur N
Nov 21 '18 at 9:04
I am not sure but Socket.io might be causing the bug?
– G'ofur N
Nov 21 '18 at 9:04
I have a serverMiddleware but I don't import it into server/index.js. I have it in api/test.js and export it with
module.exports = {path: "/api/test", handler: app}
then in nuxt.config.js serverMiddleware: ['~/api/test'],
. This works but I haven't run build yet.– Andrew1325
Nov 21 '18 at 8:50
I have a serverMiddleware but I don't import it into server/index.js. I have it in api/test.js and export it with
module.exports = {path: "/api/test", handler: app}
then in nuxt.config.js serverMiddleware: ['~/api/test'],
. This works but I haven't run build yet.– Andrew1325
Nov 21 '18 at 8:50
I also tried that. But it did not helped me cause it is programmatically same
– G'ofur N
Nov 21 '18 at 8:54
I also tried that. But it did not helped me cause it is programmatically same
– G'ofur N
Nov 21 '18 at 8:54
maybe need to show us your api code
– Andrew1325
Nov 21 '18 at 8:58
maybe need to show us your api code
– Andrew1325
Nov 21 '18 at 8:58
I updated the question
– G'ofur N
Nov 21 '18 at 9:04
I updated the question
– G'ofur N
Nov 21 '18 at 9:04
I am not sure but Socket.io might be causing the bug?
– G'ofur N
Nov 21 '18 at 9:04
I am not sure but Socket.io might be causing the bug?
– G'ofur N
Nov 21 '18 at 9:04
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53407473%2fnuxtjs-servermiddleware-causing-error-on-production%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53407473%2fnuxtjs-servermiddleware-causing-error-on-production%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I have a serverMiddleware but I don't import it into server/index.js. I have it in api/test.js and export it with
module.exports = {path: "/api/test", handler: app}
then in nuxt.config.jsserverMiddleware: ['~/api/test'],
. This works but I haven't run build yet.– Andrew1325
Nov 21 '18 at 8:50
I also tried that. But it did not helped me cause it is programmatically same
– G'ofur N
Nov 21 '18 at 8:54
maybe need to show us your api code
– Andrew1325
Nov 21 '18 at 8:58
I updated the question
– G'ofur N
Nov 21 '18 at 9:04
I am not sure but Socket.io might be causing the bug?
– G'ofur N
Nov 21 '18 at 9:04