簡體   English   中英

如何將代理與 vite(vue 前端)和 django rest 框架一起使用

[英]How to use proxy with vite (vue frontend) and django rest framework

So, you know when you access a view with django rest api on the browser, you get an html page, and when you send something like an ajax request, you get the json? 我試圖弄清楚如何弄亂 vite 的代理設置,但我找不到一個像樣的文檔。 我想將 '/' 重定向到 'http://localhost:8000/api',但確實發生了奇怪的行為。 如果我在 localhost:8000/api 上有一條路線,我可以這樣做:

//vite.config.js
export default defineConfig({
    plugins: [vue()],
    server: {
        proxy: {
            //Focus here
            '/api': {
                target: 'http://localhost:8000',
                changeOrigin: true,
                rewrite: (path) => { console.log(path); return path.replace('/^\/api/', '') }
            }
        }
    }
})
//todo-component.vue
export default {
    data() {
        return {
            todos: []
        }
    },
    components: {
        TodoElement
    },
    beforeCreate() {
                       //Focus here as well 
        this.axios.get('/api').then((response) => {
            this.todos = response.data
        })
            .catch((e) => {
                console.error(e)
            })
    }

}

這將按預期返回 json 響應。 但是,如果我嘗試讓“/”路由到“localhost:8000/api/”,如下所示:

export default defineConfig({
    plugins: [vue()],
    server: {
        proxy: {
            //change here
            '/': {
                target: 'http://localhost:8000/api',
                changeOrigin: true,
                rewrite: (path) => { console.log(path); return path.replace('/^\/api/', '') }
            }
        }
    }
})
import TodoElement from "./todo-element.vue"
export default {
    data() {
        return {
            todos: []
        }
    },
    components: {
        TodoElement
    },
    beforeCreate() {
        //change here
        this.axios.get('/').then((response) => {
            this.todos = response.data
        })
            .catch((e) => {
                console.error(e)
            })
    }

}

它只是噴出 api 視圖的 html 版本,但沒有樣式,有一堆錯誤

圖片

不知道該怎么做。 如果有人能解釋這個代理是如何工作的,我真的很喜歡它。 我不想繼續寫“api/”,如果我能理解它是如何工作的,那將是非常有價值的。

你有點令人困惑,我會試着告訴你為什么。

如果將根路徑/重定向到/api ,發送到在http://localhost:3000運行的應用程序的每個請求都將轉發http://localhost:8000/api 這意味着您將無法從正在運行的應用程序中提供任何服務,但您將從配置的端點( localhost:8000/api )獲得每個請求的答案。

為了容易理解發生了什么,請記住這個vite config option (server.proxy)就像一個反向代理。 例如,我以您的應用程序的favicon.ico資源為例。

使用您當前的配置,當您嘗試從瀏覽器訪問您的應用程序時,然后從http://localhost:8000/api/favicon.ico加載/favicon.ico (和所有其他資源) ,而不是從您的應用程序加載在http://localhost:3000/favicon.ico運行。

這解釋了控制台中的所有錯誤。 同樣,例如, /static/rest_framework是從http://localhost:8000/api/而不是http://localhost:3000/加載的。

文檔很清楚,它只是理解什么是http-proxy的基礎。 要獲取更多信息,您可以前往https://github.com/http-party/node-http-proxy#core-concept

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM