From c63bee072f502be5c00c936a9816506ccb8ec56b Mon Sep 17 00:00:00 2001 From: ducklet Date: Sun, 26 Nov 2023 19:43:56 +0100 Subject: [PATCH] respect API_HOST & API_PORT env vars for dev Using Vite's proxy option allows us to avoid CORS issues when the host for Uvicorn doesn't match the host for Vite, e.g. localhost vs. 127.0.0.1. --- scripts/dev | 6 ++++++ scripts/dev-server | 7 ++++++- scripts/server | 3 ++- unwind-ui/vite.config.ts | 24 ++++++++++++++++++++---- 4 files changed, 34 insertions(+), 6 deletions(-) diff --git a/scripts/dev b/scripts/dev index dee1b94..0381aa4 100755 --- a/scripts/dev +++ b/scripts/dev @@ -2,6 +2,12 @@ cd "$RUN_DIR" +# Make Uvicorn defaults explicit. +: "${API_PORT:=8000}" +: "${API_HOST:=127.0.0.1}" +export API_PORT +export API_HOST + [ -z "${DEBUG:-}" ] || set -x exec honcho start diff --git a/scripts/dev-server b/scripts/dev-server index 7d3e2ef..c99ac4b 100755 --- a/scripts/dev-server +++ b/scripts/dev-server @@ -4,4 +4,9 @@ cd "$RUN_DIR" [ -z "${DEBUG:-}" ] || set -x -exec uvicorn unwind:create_app --factory --reload +exec uvicorn \ + --host "$API_HOST" \ + --port "$API_PORT" \ + --reload \ + --factory \ + unwind:create_app diff --git a/scripts/server b/scripts/server index 599cb7f..5f236ed 100755 --- a/scripts/server +++ b/scripts/server @@ -11,4 +11,5 @@ export UNWIND_PORT exec uvicorn \ --host 0.0.0.0 \ --port "$UNWIND_PORT" \ - --factory unwind:create_app + --factory \ + unwind:create_app diff --git a/unwind-ui/vite.config.ts b/unwind-ui/vite.config.ts index 84d4068..99d078b 100644 --- a/unwind-ui/vite.config.ts +++ b/unwind-ui/vite.config.ts @@ -1,13 +1,29 @@ import { defineConfig } from "vite" import vue from "@vitejs/plugin-vue" +// Vite defaults. +const vite_host = "localhost" +const vite_port = 3000 + +const base = process.env.BASE_URL || "/" +const proxied_api_url = `http://${vite_host}:${vite_port}/api/` +const real_api_url = `http://${process.env.API_HOST}:${process.env.API_PORT}/api/` + // https://vitejs.dev/config/ export default defineConfig({ - base: process.env.BASE_URL || "/", + base, define: { - "process.env.API_URL": JSON.stringify( - process.env.API_URL || "http://localhost:8000/api/", - ), + "process.env.API_URL": JSON.stringify(process.env.API_URL || proxied_api_url), + }, + server: { + host: vite_host, + port: vite_port, + proxy: { + [`${base}api`]: { + target: real_api_url, + prependPath: false, + }, + }, }, plugins: [vue()], })