skip to Main Content

I rewrote my whole app from vue2 in vite vue3 composition api.In development a localhost serves the frontend. The productionserver has its own https: https://api.myurl.com. See the NGINX:

//nginx

map $request_method $cors_method { //
       
    
    server {
         listen      80;
         listen      [::]:80;
         server_name myurl.com www.myurl.com;
         return 301 etc
    }
    
    server {
        listen       443 ssl http2;
        listen       [::]:443;
        server_name  myurl.com www.myurl.com;
    
        ssl_certificate //etc
        ssl_certificate_key //etc
    
        location / {
            root /../client/dist;
            try_files $uri $uri/ /index.html;
        }
        
    }

    server {
        listen 443 ssl http2;
        listen [::]:443;
        server_name api.myurl.com;
    
        ssl_certificate /etc/letsencrypt/..;
        ssl_certificate_key /etc/letsencrypt/..;
    
        
    
        location /api {
            proxy_http_version  1.1;
            //simplified
    
            proxy_pass     http://localhost:8081;
    
            if ($cors_method ~ '1') {
        
                add_header 'Access-Control-Allow-Origin' $http_origin always;
                #simplified                
            }
    
            if ($cors_method ~ '11') {
                #add_header 'Access-Control-Allow-Origin' 'https://huismap.nl' always;
                #simplified
            }

In vue2, old app the end-point depended on a env.variable:

//vue2 end point axios

export default () => {

  const instance = axios.create({
    withCredentials: true,    
    baseURL: development ? `http://localhost:8081/api` : `https://api.myurl.com/api`
    
  })
  return instance
}

In vite vue app the endpoint depends on a vite.config.js. For development it is:

//vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  server: {
    proxy: {
      "/api/": "http://localhost:8081/"
    }
  },
  plugins: [vue()],
  
})

The online documentary shows examples of end-points of server. How do I tell vue/vite that in production the end-point is ‘https://api.myurl.com/api?

2

Answers


  1. Chosen as BEST ANSWER

    Despite the fact that the docs of Vite are pretty neat. I couldn ´t find a way to get my production-server called in the vite.config.js. At the end I returned to my old point of view to declare it in the Axios endpoint and this got things working.


  2. You can use env variables with VITE_ prefix, they will be automatically imported, so you can use them in your app like this :

    import.meta.env.VITE_API_URL
    

    To define .env for production, you can create spepatrate .env.prod file:

    VITE_API_URL=https://api.myurl.com/api    
    

    And run npm with your defined flag

    npm run build -- mode=prod
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search