I Have a problem with setting API proxy in vite.config.js
when I run NPM dev to my web and want to call API it is not using the proxy that I have defined, instead it is using my host debug URL.
I am expecting it to obey my set API target http://127.0.0.1:29985
, instead it is using http://localhost:5173
as you can see in this snip from the network trace:
500 error is because the URL is wrong.
This is my JS code that calls the API
try {
const response = await axios.get("/api/Home/getdayoff");
const data = response.data;
this.populateTable(data);
} catch (error) {
console.error("Error fetching data:", error);
} finally {
table.removeAttribute("loading");
table.addEventListener("row-click", (e) => {
const selectedRow = e.detail.row;
const rowData = Array.from(selectedRow.cells).map(
(cell) => cell.innerText
);
console.log(rowData);
dialog.open = true;
const leaveType = rowData[0];
document.getElementById("type").value = leaveType;
});
}
this is my vite.config.js
where I have configured the proxy
import { sync } from "glob";
import path from "path";
import { defineConfig } from "vite";
export default defineConfig({
root: "src",
build: {
target: "es2022",
outDir: "../dist",
emptyOutDir: true,
rollupOptions: {
input: sync("./src/**/*.html".replace(/\/g, "/")),
},
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src/assets"),
},
},
server: {
host: "0.0.0.0",
proxy: {
"/api": {
target: "http://127.0.0.1:29985", //It should proxy to this url
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^/api/),
},
},
},
});
How can I get the API URL at runtime to resolve to the proxy that I have configured?