【问题标题】:How to use proxy with vite (vue frontend) and django rest framework如何在 vite(vue 前端)和 django rest 框架中使用代理
【发布时间】:2022-01-25 01:13:23
【问题描述】:

所以,你知道当你在浏览器上使用 django rest api 访问视图时,你会得到一个 html 页面,而当你发送类似 ajax 请求的东西时,你会得到 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)
            })
    }

}

它只是喷出html版本的api视图,但没有样式,有一堆错误

不知道该怎么做。如果有人能解释这个代理是如何工作的,我真的很喜欢它。我不想一直写“api/”,如果我能理解它是如何工作的,那将非常有价值。

【问题讨论】:

    标签: javascript django vue.js django-rest-framework vite


    【解决方案1】:

    你有点困惑,我会试着告诉你为什么。

    如果您将根路径 / 重定向到 /api,发送到在 http://localhost:3000 运行的应用的每个请求都将转发http://localhost:8000/api。这意味着您将无法从正在运行的应用程序中提供任何服务,但您将从配置的端点 (localhost:8000/api) 获得每个请求的答案。

    为了容易理解发生了什么,请记住这个vite config option (server.proxy) 就像一个反向代理。例如,我以您应用的favicon.ico 资源为例。

    使用您当前的配置,当您尝试从浏览器访问您的应用程序时,/favicon.ico(和所有其他资源) 然后从 http://localhost:8000/api/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

    【讨论】:

    • 谢谢,我明白了,我会看看:)
    猜你喜欢
    • 2021-09-11
    • 2016-12-18
    • 2019-01-30
    • 2019-02-26
    • 2019-06-26
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多