Trouble connecting express api to nuxt app and mongodb - node.js

It's been seriously 10 days since i'm trying to deploy my web app online. i've gone back and forth between heroku and digital ocean. nothing solved. i've asked questions here all i get is a long post with technical terms i' not able to understand. Here's my problem :
i have a nuxt app with express.js in the backend and mongodb as the database. At first i had trouble with configuring host and port for my nuxt app. once i fixed it, anoither problem appeared : i'm not receiving data from the database. i don't if it's something related to database connection or with the express api configuration.
here's my nuxt config
export default {
ssr: false,
head: {
titleTemplate: 'Lokazz',
title: 'Lokazz',
meta: [
{ charset: 'utf-8' },
{
name: 'viewport',
content: 'width=device-width, initial-scale=1'
},
{
hid: 'description',
name: 'description',
content:
'Lokazz'
}
],
link: [
{
rel: 'stylesheet',
href:
'https://fonts.googleapis.com/css?family=Work+Sans:300,400,500,600,700&subset=latin-ext'
}
]
},
css: [
'swiper/dist/css/swiper.css',
'~/static/fonts/Linearicons/Font/demo-files/demo.css',
'~/static/fonts/font-awesome/css/font-awesome.css',
'~/static/css/bootstrap.min.css',
'~/assets/scss/style.scss'
],
plugins: [
{ src: '~plugins/vueliate.js', ssr: false },
{ src: '~/plugins/swiper-plugin.js', ssr: false },
{ src: '~/plugins/vue-notification.js', ssr: false },
{ src: '~/plugins/axios.js'},
{ src: '~/plugins/lazyLoad.js', ssr: false },
{ src: '~/plugins/mask.js', ssr: false },
{ src: '~/plugins/toastr.js', ssr: false },
],
buildModules: [
'#nuxtjs/vuetify',
'#nuxtjs/style-resources',
'cookie-universal-nuxt'
],
styleResources: {
scss: './assets/scss/env.scss'
},
modules: ['#nuxtjs/axios', 'nuxt-i18n','vue-sweetalert2/nuxt', '#nuxtjs/auth-next', "bootstrap-vue/nuxt"],
bootstrapVue: {
bootstrapCSS: false, // here you can disable automatic bootstrapCSS in case you are loading it yourself using sass
bootstrapVueCSS: false, // CSS that is specific to bootstrapVue components can also be disabled. That way you won't load css for modules that you don't use
},
i18n: {
locales: [
{ code: 'en', file: 'en.json' },
],
strategy: 'no_prefix',
fallbackLocale: 'en',
lazy: true,
defaultLocale: 'en',
langDir: 'lang/locales/'
},
router: {
linkActiveClass: '',
linkExactActiveClass: 'active',
},
server: {
port: 8080, // default: 3000
host: '0.0.0.0' // default: localhost
},
auth: {
strategies: {
local: {
token: {
property: "token",
global: true,
},
redirect: {
"login": "/account/login",
"logout": "/",
"home": "/page/ajouter-produit",
"callback": false
},
endpoints: {
login: { url: "/login", method: "post" },
logout: false, // we don't have an endpoint for our logout in our API and we just remove the token from localstorage
user:false
}
}
}
},
};
here's my package.json
{
"name": "martfury_vue",
"version": "1.3.0",
"description": "Martfury - Multi-purpose Ecomerce template with vuejs",
"author": "nouthemes",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"config": {
"nuxt": {
"host": "0.0.0.0",
"port": "8080"
}
},
}
here's my repository.js file
import Cookies from 'js-cookie';
import axios from 'axios';
const token = Cookies.get('id_token');
const baseDomain = 'https://lokazzfullapp-8t7ec.ondigitalocean.app';
export const customHeaders = {
'Content-Type': 'application/json',
Accept: 'application/json'
};
export const baseUrl = `${baseDomain}`;
export default axios.create({
baseUrl,
headers: customHeaders
});
export const serializeQuery = query => {
return Object.keys(query)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
.join('&');
};
an example of an api call i make locally that works without a problem :
import Repository, { serializeQuery } from '~/repositories/Repository.js';
import { baseUrl } from '~/repositories/Repository';
import axios from 'axios'
const url = baseUrl;
export const actions = {
async getProducts({ commit }, payload) {
const reponse = await axios.get(url)
.then(response => {
commit('setProducts', response.data);
return response.data;
})
.catch(error => ({ error: JSON.stringify(error) }));
return reponse;
},
}
here's my index.js (express file)
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose')
const cors = require('cors');
//const url = 'mongodb://localhost:27017/lokazz'
const url = 'mongodb+srv://lokazz:zaki123456#cluster0.hsd8d.mongodb.net/lokazz?retryWrites=true&w=majority'
const jwt = require('jsonwebtoken')
const con = mongoose.connection
mongoose.connect(url, {useNewUrlParser:true}).then(()=>{
const app = express();
// middlleware
app.use(express.json())
app.use(cors());
//products routes
const products = require('./product/product.router');
app.use('/', products)
//users routes
const users = require('./user/user.router');
app.use('/', users)
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
}).catch(error => console.log(error.reason));
con.on('open', () => {
console.log('connected...')
})
My directory structure
the error i get after the api request, meaning it's not receving any data.
ebd1ecd.js:2 TypeError: Cannot read properties of undefined (reading 'username')
at f.<anonymous> (c88240c.js:1)
at f.t._render (ebd1ecd.js:2)
at f.r (ebd1ecd.js:2)
at wn.get (ebd1ecd.js:2)
at new wn (ebd1ecd.js:2)
at t (ebd1ecd.js:2)
at f.In.$mount (ebd1ecd.js:2)
at init (ebd1ecd.js:2)
at ebd1ecd.js:2
at v (ebd1ecd.js:2)
idk if it's a problem with mongodb connection cluster or the api call.

Related

How can I use sequelize in a Nodejs application that is using heroku postgresql database

I am creating a simple CRUD API using Nodejs, express. I need to use postgresql hosted on heroku for this app and Sequelize as ORM. However interaction with database is not working.
Here is my code
index.js
const express = require('express')
require('dotenv').config()
const Sequelize = require('sequelize')
const usersRouter = require('./routers/users')
const sequelize = new Sequelize(process.env.DATABASE_URL, {
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false
}
}
})
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.')
})
.catch((err) => {
console.error('Unable to connect to the database:', err)
})
const app = express()
const bodyParser = require('body-parser')
const cors = require('cors')
app.use(cors())
app.use(express.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
const port = 3000
app.get('/', (req, res) => {
res.send('Nodejs mentoring 2022!')
})
app.use('/users', usersRouter)
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
/router/users
const express = require('express')
const router = express.Router()
connst {
getAllUsers
} = require('./controllers/userControllers')
//user routes
router
.route('/')
.get(getAllUsers)
module.exports = router
userControllers
const { Sequelize } = require('sequelize')
const sequelize = new Sequelize(process.env.DATABASE_URL, {
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false
}
}
})
const User = require('./../../models/user')(sequelize)
const createError = require('http-errors')
exports.getAllUsers = async (req, res, next) => {
try {
const users = await User.findAll()
if (!users) throw new createError.NotFound()
res.status(200).send(users)
} catch (e) {
next(e)
}
}
models/user
const { DataTypes } = require('sequelize')
module.exports = (sequelize) => {
const User = sequelize.define(
'User',
{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
allowNull: false
},
login: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
},
age: {
type: DataTypes.INTEGER,
allowNull: false
},
is_deleted: {
type: DataTypes.BOOLEAN,
allowNull: false
}
},
{
timestamps: false
}
)
return User
}
package.json
{
"name": "nodejs-mentoring-2022",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/mamuna36/nodejs-mentoring-2022.git"
},
"author": "",
"license": "ISC",
"engines" : {
"node": "16.14.2"
},
"bugs": {
"url": "https://github.com/mamuna36/nodejs-mentoring-2022/issues"
},
"homepage": "https://github.com/mamuna36/nodejs-mentoring-2022#readme",
"devDependencies": {
"nodemon": "^2.0.20"
},
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-joi-validation": "^5.0.1",
"joi": "^17.6.3",
"pg": "^8.8.0",
"sequelize": "^6.25.3",
"sqlite3": "^5.1.2"
}
}
when I try to test the getAllUsers endpoint in postman I get this error
Executing (default): SELECT "id", "login", "password", "age", "is_deleted" FROM "Users" AS "User";
Error
at Query.run (C:\Users\Mamuna_Anwar\VScodeProjects\nodejs-mentoring- 2022\node_modules\sequelize\lib\dialects\postgres\query.js:50:25)
at C:\Users\Mamuna_Anwar\VScodeProjects\nodejs-mentoring-2022\node_modules\sequelize\lib\sequelize.js:314:28
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async PostgresQueryInterface.select (C:\Users\Mamuna_Anwar\VScodeProjects\nodejs-mentoring-2022\node_modules\sequelize\lib\dialects\abstract\query-interface.js:407:12)
at async Function.findAll (C:\Users\Mamuna_Anwar\VScodeProjects\nodejs-mentoring-2022\node_modules\sequelize\lib\model.js:1134:21)
at async exports.getAllUsers (C:\Users\Mamuna_Anwar\VScodeProjects\nodejs-mentoring-2022\routers\controllers\userControllers.js:39:19)

Quasar-cli-vite devServer proxy not working

I'm starting to test Quasar framework and I want to proxy some url to my local backend but the configuration doesn't seem to work (documentation here).
The part of my quasar.config.js where the proxy should be configured:
devServer: {
// https: true
proxy: {
'/association': {
target: 'http://localhost:8080',
changeOrigin: true,
}
},
open: false,
},
I've also tried to do it inline '/association': 'http://localhost:8080' with the same result. My request are not redirect and query on port 80: http://localhost/association/setProducerStats
Anyone already managed to configure the proxy ?
Quasar is already running itself on port 8080 - try to use a different port for your local backend, or add port: 8090 to the devServer config.
Example config for Vite:
// vite.config.js
import { defineConfig } from 'vite';
import { resolve } from 'path';
import vue from '#vitejs/plugin-vue';
import { quasar, transformAssetUrls } from '#quasar/vite-plugin';
import viteStylelint from './plugins/stylelint';
import eslintPlugin from 'vite-plugin-eslint';
import Components from 'unplugin-vue-components/vite';
import { QuasarResolver } from 'unplugin-vue-components/resolvers';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue({
template: { transformAssetUrls }
}),
quasar({
autoImportComponentCase: 'pascal',
sassVariables: 'src/quasar-variables.sass'
}),
viteStylelint({
exclude: /node_modules|.*uno\.css/
}),
eslintPlugin({
cache: false
}),
Components({
resolvers: [QuasarResolver()],
include: [/\.vue$/],
exclude: [/node_modules/, /\.git/, /\.nuxt/],
})
],
resolve: {
alias: {
src: resolve(__dirname, './src'),
'#': resolve(__dirname, './src'),
},
},
server: {
https: false,
port: 9000,
proxy: {
'/api': {
target: 'https://api.example.com',
changeOrigin: true,
secure: true,
//rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
build: {
terserOptions: {
compress: {
drop_console: true,
},
},
// reportCompressedSize: true,
chunkSizeWarningLimit: 1024,
rollupOptions: {
output: {
manualChunks(id)
{
if (id.includes('/node_modules/'))
{
const modules = ['quasar', '#quasar', 'vue', '#vue'];
const chunk = modules.find((module) => id.includes(`/node_modules/${module}`));
return chunk ? `vendor-${chunk}` : 'vendor';
}
},
},
},
},
});

Deploy Angular App w/ Proxy for One Route

I have an Angular app w/ a proxy that's working well in local. There's one route that utilizes it with a Node API call.
Node.js
const express = require('express');
const api_service = require('./apiService');
const app = express();
app.get('/getData/:date', (req, res) => {
const date = req.params.date;
api_service.fetchData(...)
.then(response => {
res.json(response)
})
.catch(error => {
res.send(error)
})
})
app.listen(3000, () => {
console.log("Server started in port 3000!");
});
Function in my Angular Service:
fetchData(date: string) {
const requestOptions: Object = {
responseType: 'text',
};
this._http
.get<string>('/api/getData/' + date)
.pipe(
map((data) => {
this.result = data;
})
)
.subscribe((data) => {
this.mediaSource.next(this.result);
if (Object.keys(this.result).length != 0) {
this.history.push(this.result);
}
});
}
proxy-prod.config.json
{
"/api/*": {
"target": "https://example.com",
"secure": false,
"changeOrigin": true,
"logLevel": "debug",
"pathRewrite": { "^/api": "" }
}
}
proxy-local.conf.json
{
"/api/*": {
"target": "http://localhost:3000",
"pathRewrite": {
"^/api": ""
},
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
angular.json
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "ui-dev:build",
"proxyConfig": "proxy-local.conf.json"
},
"configurations": {
"production": {
"browserTarget": "ui-dev:build:production",
"proxyConfig": "proxy-prod.config.json"
}
}
},
ng serve works perfectly.
ng serve --prod and ng build --aot --prod --output-hashing none do not.
The error I'm getting is:
headers: d, status: 200, statusText: 'OK', url: 'myexample.com', ok: false
I've tried this in my request but they cause errors too:
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
{ headers, responseType: 'text'}
Been searching, testing, and dissecting code for many hours and not sure how to proceed. Can you anyone assist?
Thanks

unhandledRejection The "path" argument must be of type string or an instance of Buffer or URL. Received undefined - Nuxtjs

When I try to build or run nuxi dev to start my application for development this error comes up and application don't work properly.
I deleted all lock files, removed module folder and run yarn install but this is still there,
This is the exception trace info from compiler.
at readFileSync (node:fs:453:35)
at extractMeta (node_modules\nuxt-route-meta\dist\index.js:52:51)
at parseRoutes (node_modules\nuxt-route-meta\dist\index.js:149:57)
at /D:/Frontend/nuxt2/node_modules/#nuxt/kit/dist/index.mjs:477:37
at /D:/Frontend/nuxt2/node_modules/hookable/dist/index.mjs:39:70
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Object.getContents (/D:/Frontend/nuxt2/node_modules/nuxt3/dist/chunks/index.mjs:348:9)
at async /D:/Frontend/nuxt2/node_modules/nuxt3/dist/chunks/index.mjs:1338:22
at async Promise.all (index 16)
Here is the .env file
BASE_URL=http://localhost:8000
ECHO_PORT=
HOSTNAME=http://localhost:3000
STRIPE_KEY=x
ALGOLIA_APP_ID=y
ALGOLIA_API_KEY=z
And here is the nuxt.config.ts file content.
import getSiteMeta from './utils/getSiteMeta'
import { cloneDeep } from 'lodash'
const meta = getSiteMeta()
// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config
export default defineNuxtConfig({
ssr: false,
// server: {
// host: process.env.HOST || 'localhost' // default: localhost
// },
sitemap: [
{
hostname: process.env.BASE_URL || 'http://localhost:3000',
path: '/sitemap.xml',
gzip: true,
},
],
// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
htmlAttrs: {
lang: 'en-GB',
},
title:
'Family Tree 365 - Start your family tree today - free! Your first tree is 100% free. Sign-up to begin your genealogy journey today!',
meta: [
...meta,
{ charset: 'utf-8' },
{ name: 'HandheldFriendly', content: 'True' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ property: 'og:site_name', content: 'Family Tree 365' },
{
hid: 'description',
name: 'description',
content:
'Our user-friendly yet powerful platform lets you create your own family tree the quick and easy way. No technical knowledge is required. Start your family tree today - free!',
},
{ property: 'og:image:width', content: '2500' },
{ property: 'og:image:height', content: '780' },
{ name: 'twitter:site', content: '#familytree365' },
{ name: 'twitter:card', content: 'summary_large_image' },
],
link: [
{ rel: 'icon', href: '/favicon.ico' },
{
hid: 'canonical',
rel: 'canonical',
href: process.env.BASE_URL,
},
],
},
// Global CSS: https://go.nuxtjs.dev/config-css
// css: ["~/assets/style/enso.scss", "animate.css/animate.compat.css"],
css: [
'animate.css/animate.compat.css',
'~/assets/css/base.css',
'~/assets/style/enso.scss',
'~/assets/css/fontawesome.min.css',
],
router: {
middleware: 'auth'
},
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
'~/plugins/bootEnums.js',
'~/plugins/i18n.js',
'~/plugins/pRoute.js',
'~/plugins/filters.js',
'~/plugins/numberFormat.js',
'~/plugins/shortNumber.js',
'~/plugins/toastr.js',
'~/plugins/fontawesome.js',
'~/plugins/themesSettingRegister.js',
'~/plugins/bookmarksSettingRegister.js',
'~/plugins/tutorialSettingRegister.js',
'~/plugins/notificationsRegister.js',
'~/plugins/localisationRegister.js',
'~/plugins/ioRegister.js',
'~/plugins/tasksNavbarRegister.js',
'~/plugins/usersRegister.js',
'~/plugins/Validator.js',
'~/plugins/date-fns/format.js',
'~/plugins/date-fns/formatDistance.js',
'~/plugins/vue-select.js',
'~/plugins/vuelidate.js',
'~/plugins/vue-gtag.client.js',
//'~/plugins/echo.js',
"~/plugins/vue-fb-customer-chat.js",
{src: '~/plugins/vue-stripe.js', ssr: false},
],
// Auto import components: https://go.nuxtjs.dev/config-components
// components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
// https://go.nuxtjs.dev/eslint
// "#nuxtjs/eslint-module",
'#nuxtjs/fontawesome',
'#nuxtjs/router-extras',
'#nuxtjs/vuetify',
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'nuxt-vuex-router-sync',
'nuxt-route-meta',
],
fontawesome: {
icons: {
solid: true,
brands: true,
},
},
nuxtContentAlgolia: {
appId: process.env.ALGOLIA_APP_ID,
apiKey: process.env.ALGOLIA_API_KEY,
paths: [
{
name: 'articles',
index: 'articles',
fields: ['title', 'description', 'bodyPlainText'],
},
],
},
publicRuntimeConfig: {
axios: {
browserBaseURL: process.env.BASE_URL || 'http://localhost:3000',
proxyHeaders: false,
},
appEnv: process.env.APP_ENV || 'production',
},
env: {
STRIPE_PK: process.env.STRIPE_KEY,
baseUrl: process.env.BASE_URL ||'http://localhost:3000',
},
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
proxyHeaders: false,
proxy: true,
credentials: true,
},
proxy: {
'/api/': process.env.BASE_URL || 'http://localhost:8000',
'/broadcasting/': process.env.BASE_URL || 'http://localhost:8000',
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
filenames: {
app: ({ isDev }) => (isDev ? '[name].js' : '[chunkhash].js'),
chunk: ({ isDev }) => (isDev ? '[name].js' : '[chunkhash].js'),
css: ({ isDev }) => (isDev ? '[name].css' : '[contenthash].css'),
img: ({ isDev }) => (isDev ? '[path][name].[ext]' : 'img/[hash:7].[ext]'),
font: ({ isDev }) =>
isDev ? '[path][name].[ext]' : 'fonts/[hash:7].[ext]',
video: ({ isDev }) =>
isDev ? '[path][name].[ext]' : 'videos/[hash:7].[ext]',
},
transpile: [
'#enso-ui/strings',
'vee-validate/dist/rules',
'#enso-ui/enums',
'#sentry/browser',
'#sentry/integrations',
'#enso-ui/sentry',
'#enso-ui/route-mapper',
'd3-dag',
],
extend(config) {
const isScssRule = (rule) => rule.test.toString() === '/\\.scss$/i'
config.module.rules.forEach((rule) => {
if (isScssRule(rule)) {
const normalRule = rule.oneOf.find(
({ resourceQuery, test }) =>
resourceQuery === undefined && test === undefined
)
const lazyRule = cloneDeep(normalRule)
lazyRule.test = /\.lazy\.scss$/
const idx = lazyRule.use.findIndex(({ loader }) =>
loader.includes('vue-style-loader')
)
if (idx > -1) {
lazyRule.use.splice(idx, 1, {
loader: 'style-loader',
options: {
injectType: 'lazyStyleTag',
insert: function insertAtTop(element) {
const parent = document.querySelector('head')
parent.insertBefore(element, parent.firstChild)
},
},
})
}
rule.oneOf.push(lazyRule)
}
})
// const scssRules = config.module.rules.find('scss').oneOfs;
// const normalRule = scssRules.store.get('normal');
// const lazyRule = config.module.rules.find('scss').oneOf('scss-lazy');
// normalRule.uses.values().forEach(use => {
// if (use.name !== 'vue-style-loader') {
// lazyRule.use(use.name).merge(use.entries());
// return;
// }
// lazyRule.use('style-loader')
// .loader('style-loader')
// .options({
// injectType: 'lazyStyleTag',
// insert: function insertAtTop(element) {
// const parent = document.querySelector('head');
// parent.insertBefore(element, parent.firstChild);
// },
// });
// });
// lazyRule.test(/\.lazy\.scss$/);
// scssRules.store.delete('normal', 'scss-lazy');
// scssRules.store.set('scss-lazy', lazyRule);
// scssRules.store.set('normal', normalRule);
},
},
})
Have a look at my package.json file
{
"private": true,
"scripts": {
"dev": "nuxi dev",
"build": "nuxi build",
"start": "node .output/server/index.mjs"
},
"devDependencies": {
"#fortawesome/free-brands-svg-icons": "^6.0.0",
"#nuxtjs/fontawesome": "^1.1.2",
"#nuxtjs/vuetify": "^1.12.3",
"nuxt3": "^3.0.0-27444169.120ee4f"
},
"dependencies": {
"#enso-ui/bulma": "^5.0.7",
"#enso-ui/charts": "^4.0.0",
"#enso-ui/laravel-validation": "^2.0.6",
"#enso-ui/transitions": "^2.0.11",
"#fortawesome/fontawesome-svg-core": "^1.3.0",
"#fortawesome/free-solid-svg-icons": "^6.0.0",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/router-extras": "^1.1.1",
"#nuxtjs/style-resources": "^1.2.1",
"chart": "^0.1.2",
"chart.js": "^2.9.4",
"node-sass": "^7.0.1",
"nuxt-route-meta": "^2.3.4",
"nuxt-vuex-router-sync": "^0.0.3",
"postcss": "^8.2.15",
"resolve": "1.20.0",
"vue": "^3.2.31",
"vue-chartjs": "^3.5.1",
"vue-gtag-next": "^1.14.0",
"vue-loading-overlay": "5.0",
"vuex": "^4.0.2"
}
}

configuring base url nuxt for digital ocean deployement

i'm building ecommerce web app using nuxt and node.js/express. when i'm building locally i have no problem making axios api calls. base url is configured as the following
const baseDomain = 'http://localhost:8080/';
then all i do is
async getProducts({ commit }, payload) {
const reponse = await Repository.get(
`${baseUrl}/products?${serializeQuery(payload)}`
)
.then(response => {
commit('setProducts', response.data);
return response.data;
})
.catch(error => ({ error: JSON.stringify(error) }));
return reponse;
},
now the problem is when i move my whole app to digital ocean, i tried the following changes
const baseDomain = 'https://0.0.0.0:8080/';
my nuxt.js config
export default {
ssr: false,
head: {
titleTemplate: 'Lokazz',
title: 'Lokazz',
meta: [
{ charset: 'utf-8' },
{
name: 'viewport',
content: 'width=device-width, initial-scale=1'
},
{
hid: 'description',
name: 'description',
content:
'Lokazz'
}
],
link: [
{
rel: 'stylesheet',
href:
'https://fonts.googleapis.com/css?family=Work+Sans:300,400,500,600,700&amp;subset=latin-ext'
}
]
},
css: [
'swiper/dist/css/swiper.css',
'~/static/fonts/Linearicons/Font/demo-files/demo.css',
'~/static/fonts/font-awesome/css/font-awesome.css',
'~/static/css/bootstrap.min.css',
'~/assets/scss/style.scss'
],
plugins: [
{ src: '~plugins/vueliate.js', ssr: false },
{ src: '~/plugins/swiper-plugin.js', ssr: false },
{ src: '~/plugins/vue-notification.js', ssr: false },
{ src: '~/plugins/axios.js'},
{ src: '~/plugins/lazyLoad.js', ssr: false },
{ src: '~/plugins/mask.js', ssr: false },
{ src: '~/plugins/toastr.js', ssr: false },
],
buildModules: [
'#nuxtjs/vuetify',
'#nuxtjs/style-resources',
'cookie-universal-nuxt'
],
styleResources: {
scss: './assets/scss/env.scss'
},
modules: ['#nuxtjs/axios', 'nuxt-i18n','vue-sweetalert2/nuxt', '#nuxtjs/auth-next', "bootstrap-vue/nuxt"],
bootstrapVue: {
bootstrapCSS: false, // here you can disable automatic bootstrapCSS in case you are loading it yourself using sass
bootstrapVueCSS: false, // CSS that is specific to bootstrapVue components can also be disabled. That way you won't load css for modules that you don't use
},
i18n: {
locales: [
{ code: 'en', file: 'en.json' },
],
strategy: 'no_prefix',
fallbackLocale: 'en',
lazy: true,
defaultLocale: 'en',
langDir: 'lang/locales/'
},
router: {
linkActiveClass: '',
linkExactActiveClass: 'active',
},
server: {
port: 8080, // default: 3000
host: '0.0.0.0' // default: localhost
/// this one works fine , the digital ocean support team told me to do this.
},
auth: {
strategies: {
local: {
token: {
property: "token",
global: true,
},
redirect: {
"login": "/account/login",
"logout": "/",
"home": "/page/ajouter-produit",
"callback": false
},
endpoints: {
login: { url: "/login", method: "post" },
logout: false, // we don't have an endpoint for our logout in our API and we just remove the token from localstorage
user:false
}
}
}
},
};
package.json file
{
"name": "martfury_vue",
"version": "1.3.0",
"description": "Martfury - Multi-purpose Ecomerce template with vuejs",
"author": "nouthemes",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"config": {
"nuxt": {
"host": "0.0.0.0",
"port": "8080"
}
},
}
server index.js config
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose')
const cors = require('cors');
const url = 'mongodb+srv://****************************' // this works fine i manage to pull data from the cluster without a problem
const jwt = require('jsonwebtoken')
mongoose.connect(url, {useNewUrlParser:true}).then(()=>{
const app = express();
// middlleware
app.use(express.json())
app.use(cors());
//products routes
const products = require('./product/product.router');
app.use('/', products)
//users routes
const users = require('./user/user.router');
app.use('/', users)
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Server started on port ${port}`));
}).catch(error => console.log(error.reason));
const con = mongoose.connection
con.on('open', () => {
console.log('connected...')
})
here's my github repo and file structure. the server and api folder is lokazz_api.
I would recommend you use Environment variables for this.
Install dotenv in your project and then configure it in your nuxt.config.js file.
Create a .env file in your root directory, and then set a key-value pair like this:
VUE_APP_BASE_URL="<value>"
Note you need to prefix your keys with VUE_APP.
Your .env should look like this:
VUE_APP_BASE_URL="http://localhost:8080/"
You can modify your variable to this: const baseDomain = process.env.BASE_URL;
Remember to add the .env file in the .gitignore file.
On your digital ocean terminal, you can create a .env file using the touch .env command, and then use Vim or Nano to modify the file.
If your project runs fine with an .env file, it should work as good on production.
DO NOT commit .env but rather aim to your Digitalocean dashboard and look in the settings. You should see a place where you can input your pair and then proceed.
As shown here: https://docs.digitalocean.com/products/app-platform/how-to/use-environment-variables/#using-bindable-variables-within-environment-variables

Resources