This is the first time I'm using sequelize and i ran into a problem with creating a table in PostgreSQL. Server is running without any errors but its seems that sequelize don't do anything. I post my code below in hope that you can help me with this problem.
This is my server.js file
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// database
const db = require("./app/models");
const Role = db.role;
// db.sequelize.sync();
// force: true will drop the table if it already exists
db.sequelize.sync({force: true}).then(() => {
console.log('Drop and Resync Database with { force: true }');
initial();
});
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to bezkoder application." });
});
// routes
require('./app/routes/auth.routes')(app);
require('./app/routes/user.routes')(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
function initial() {
Role.create({
id: 1,
naziv: "user"
});
Role.create({
id: 2,
naziv: "moderator"
});
Role.create({
id: 3,
naziv: "admin"
});
}
my db.config
module.exports = {
HOST: "localhost",
USER: "postgres",
PASSWORD: "sarke",
DB: "elposlovanje",
dialect: "postgres",
port: 5432,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
my index.js from models
const config = require("../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(
config.DB,
config.USER,
config.PASSWORD,
{
host: config.HOST,
dialect: config.dialect,
port: config.port,
pool: {
max: config.pool.max,
min: config.pool.min,
acquire: config.pool.acquire,
idle: config.pool.idle
}
}
);
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.user = require("../models/user.model.js")(sequelize, Sequelize);
db.role = require("../models/role.model.js")(sequelize, Sequelize);
db.role.belongsToMany(db.user, {
through: "user_roles",
foreignKey: "roleId",
otherKey: "userId"
});
db.user.belongsToMany(db.role, {
through: "user_roles",
foreignKey: "userId",
otherKey: "roleId"
});
db.ROLES = ["user", "admin", "moderator"];
module.exports = db;
role from models
module.exports = (sequelize, Sequelize) => {
const Role = sequelize.define("roles", {
id: {
type: Sequelize.INTEGER,
primaryKey: true
},
naziv: {
type: Sequelize.STRING
}
});
return Role;
};
and user from model
module.exports = (sequelize, Sequelize) => {
const User = sequelize.define("users", {
ime: {
type: Sequelize.STRING
},
prezime: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
lozinka: {
type: Sequelize.STRING
},
brojindexa: {
type: Sequelize.STRING
}
});
return User;
};
Output after running node server.js is
Server is running on port 8080.
my package.json
{
"name": "node-js-jwt-auth-postgresql",
"version": "1.0.0",
"description": "Node.js Demo for JWT Authentication with PostgreSQL",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"express",
"jwt",
"authentication",
"postgresql"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"pg": "^7.18.2",
"pg-hstore": "^2.3.3",
"sequelize": "^5.22.3"
},
"devDependencies": {
"sequelize-cli": "^6.2.0"
}
}
i found out the problem was in the version of pg
Related
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)
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"
}
}
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.
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&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
I have 5 endpoint with 4 methods implemented. For GET, POST, DELETE all of them goes well. I don't understand why PUT method doesn't work. In my case, I need to update column first_name and last_name but it send me error like this:
{
"name": "SequelizeDatabaseError",
"parent": {
"length": 221,
"name": "error",
"severity": "ERROR",
"code": "42703",
"where": "PL/pgSQL function last_updated() line 3 at assignment",
"file": "d:\\pginstaller_13.auto\\postgres.windows-x64\\src\\pl\\plpgsql\\src\\pl_exec.c",
"line": "5170",
"routine": "exec_assign_value",
"sql": "UPDATE \"actors\" SET \"first_name\"=$1,\"last_name\"=$2,\"updatedAt\"=$3 WHERE \"actor_id\" = $4",
"parameters": [
"Anne ",
"Anne",
"2020-10-29 02:54:11.642 +00:00",
"200"
]
},
"original": {
"length": 221,
"name": "error",
"severity": "ERROR",
"code": "42703",
"where": "PL/pgSQL function last_updated() line 3 at assignment",
"file": "d:\\pginstaller_13.auto\\postgres.windows-x64\\src\\pl\\plpgsql\\src\\pl_exec.c",
"line": "5170",
"routine": "exec_assign_value",
"sql": "UPDATE \"actors\" SET \"first_name\"=$1,\"last_name\"=$2,\"updatedAt\"=$3 WHERE \"actor_id\" = $4",
"parameters": [
"Anne ",
"Anne",
"2020-10-29 02:54:11.642 +00:00",
"200"
]
},
"sql": "UPDATE \"actors\" SET \"first_name\"=$1,\"last_name\"=$2,\"updatedAt\"=$3 WHERE \"actor_id\" = $4",
"parameters": [
"Anne ",
"Anne",
"2020-10-29 02:54:11.642 +00:00",
"200"
]
}
This is how i tested in Postman
And this is my models:
const actor = (sequelize, DataTypes) => {
const Actor = sequelize.define('actor', {
actor_id: {
type: DataTypes.INTEGER,
primaryKey: true,
unique: true,
autoIncrement: true,
allowNull: false,
},
first_name: {
type: DataTypes.STRING(45),
allowNull: false,
},
last_name: {
type: DataTypes.STRING(45),
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
},
updatedAt: {
type: DataTypes.DATE,
},
});
return Actor;
};
export default actor;
Help me, please. I have searched all around for the answer but still stuck.
UPDATE:
Here is my code when instantiate Sequelize:
import Sequelize from 'sequelize';
const sequelize = new Sequelize(
process.env.DATABASE,
process.env.DATABASE_USER,
process.env.DATABASE_PASSWORD,
{
dialect: 'postgres',
},
);
const models = {
Actor: sequelize.import('./actor'),
};
export { sequelize };
export default models;
And this is my app.js:
import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import path from 'path';
import models, { sequelize } from './models';
import routes from './routes';
const app = express();
// Application-Level Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(async (req, res, next) => {
req.context = {
models,
me: await models.Actor,
};
next();
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
// Routes
app.get('/', async (req, res) => {
try {
res.render('index');
} catch (error) {
res.send(error);
}
});
app.use('/actor', routes.actor);
// 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');
});
// Start
sequelize.sync().then(async () => {
app.listen(process.env.PORT, () =>
console.log(`App listening on port ${process.env.PORT}!`),
);
});
module.exports = app;
Also, this is my actual table structure
[SOLVED]
This happen because I have deleted one column named "last_updated" that used as trigger when UPDATE, image . Now I disable that trigger and can successfully update.
My mistake, this DB I import from here and didn't give attention to it