0

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. enter image description here

Sb Zakaria
  • 311
  • 6
  • 18

2 Answers2

0

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.

wisdom
  • 230
  • 2
  • 10
  • Please do not use `dotenv` since it's already baked into Nuxt. Rather use publicRuntime as explained here: https://stackoverflow.com/a/67705541/8816585 – kissu Sep 12 '21 at 04:05
  • @wisdom but the problem is it won't work when i deploy it on digital ocean. I need it to work there .... – Sb Zakaria Sep 12 '21 at 08:19
  • @SbZakaria why? You can totally set env variables there too. I don't see the blocker here. – kissu Sep 12 '21 at 10:32
  • @kissu so what you are saying is that if i deploy it with with the VUE_APP_BASE_URL="localhost:8080" everything will work fine?? – Sb Zakaria Sep 12 '21 at 10:44
  • Yes, this will work only if your local is using the same config. – wisdom Sep 12 '21 at 21:24
  • @SbZakaria you probably need some different values on production but the idea is the same yeah. Usually you do have URL/crrdentials/alike for dev and other ones for production. – kissu Sep 12 '21 at 22:06
0

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

kissu
  • 40,416
  • 14
  • 65
  • 133