Ely*_*ium 2 javascript django django-rest-framework vue.js vite
所以,你知道当你在浏览器上使用 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/', '') }
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
//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)
})
}
}
Run Code Online (Sandbox Code Playgroud)
这将按预期返回 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/', '') }
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
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)
})
}
}
Run Code Online (Sandbox Code Playgroud)
它只是输出 api 视图的 html 版本,但没有样式,有一堆错误

不知道该怎么办。如果有人可以解释这个代理是如何工作的,我真的很喜欢它。我不想继续写“api/”,如果我能够理解它是如何工作的,那将非常有价值。
你有点令人困惑,我会尽力向你展示原因。
如果您将根路径重定向/到/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
| 归档时间: |
|
| 查看次数: |
9427 次 |
| 最近记录: |