Have you ever noticed the difference between accessing a view with Django Rest API on a browser versus sending an Ajax request and receiving JSON? I'm currently trying to modify the proxy settings for Vite, but I'm struggling to find comprehensive documentation on it. My goal is to redirect '/' to 'http://localhost:8000/api', but I'm encountering some strange behavior. If I have a route on localhost:8000/api, I can use:
//vite.config.js
export default defineConfig({
plugins: [vue()],
server: {
proxy: {
//Pay attention 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 too
this.axios.get('/api').then((response) => {
this.todos = response.data
})
.catch((e) => {
console.error(e)
})
}
}
This setup returns the expected JSON response. However, if I try to redirect '/' to 'localhost:8000/api/' like this:
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() {
//make changes here
this.axios.get('/').then((response) => {
this.todos = response.data
})
.catch((e) => {
console.error(e)
})
}
}
It displays the HTML version of the API view without styling and generates numerous errors.
I'm quite lost on what to do next. If anyone could offer an explanation on how this proxy operates, I would greatly appreciate it. Avoiding constant writing of "api/" would be extremely helpful if I could grasp the functionality behind this process.