【发布时间】: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