Utilizing a Proxy with Vite for Vue Frontend in Conjunction with Django Rest Framework

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.

Answer №1

Your explanation is a bit unclear and I will break it down for you.

By redirecting the root path / to /api, all requests made to your app running at http://localhost:3000 will be forwarded to http://localhost:8000/api. This means that your app won't serve any content directly; instead, responses will come from the configured endpoint (localhost:8000/api) for every request.

To simplify, think of this

vite config option (server.proxy)
as a reverse proxy. For instance, let's consider the favicon.ico resource in your app.

With the current setup, when you access your app from the browser, the /favicon.ico file (and other resources) are loaded from

http://localhost:8000/api/favicon.ico
, not from
http://localhost:3000/favicon.ico
.

This explains the errors you're seeing in the console. For example, /static/rest_framework is fetched from http://localhost:8000/api/ instead of http://localhost:3000/.

The concept is clarified in the documentation - it's all about understanding how a http-proxy operates. For further details, check out https://github.com/http-party/node-http-proxy#core-concept

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Have you ever wondered how the automatic video play on scroll feature works on Tiktok.com and YouTube shorts when using a mobile device?

My goal with React JS is to develop a website similar to Tiktok, where the video below will automatically play with sound as the user scrolls down. I attempted to set this up using window.addEventListener("scroll",...), but after looking into it further, ...

AngularJS directive ngShow not working properly

It seems like I'm encountering some scope issues that I can't seem to resolve. Here's a rundown of the problem: I'm trying to create a custom directive called "my-create-content" that will insert an "img" HTML template into the element ...

The failure of a unit test involving Jest and try-catch

I am facing an issue with creating unit tests using jest. exportMyData.js const createJobTrasferSetArray = async () => { const data = exportData(); const jobTransferSet = []; try { data.forEach((element) => { const JobPathArray = el ...

Is it possible to conduct a comparison between two arrays by utilizing a computed property in Vue.js?

Apologies if my explanation was not clear. I am trying to implement an edit amenity feature similar to Airbnb. I have an array called "Amenity" which stores id and name values. I then loaded all the amenities for house_id = 2 into an array named "house_am ...

I can't find my unit test in the Test Explorer

I'm currently working on configuring a unit test in Typescript using tsUnit. To ensure that everything is set up correctly, I've created a simple test. However, whenever I try to run all tests in Test Explorer, no results are displayed! It appear ...

Ways to modify the end result using callback information

In my scenario, I am working with an object that has keys id and name as shown below. The goal is to retrieve the customer name based on the id and then update the object accordingly. Const arr=[{id:1,name:''},{id:2,name:''}]; ...

Storing the value of the current vertical scroll position in a variable using jQuery

I'm currently dealing with a challenge that involves using the value of (window).scrollTop() as a crucial variable in my project. What I aim to accomplish is to retrieve and utilize the specific scroll value at a particular moment within an if stateme ...

An AngularJS project utilizing exclusively EJB

Can an AngularJS application be built directly with EJB without needing to expose them as REST services? Many examples on the internet show that eventually REST services are required to provide data to AngularJS. This means that EJB methods must be expos ...

The HTML Canvas arc function fails to properly align curves

UPDATE Upon further investigation, I've discovered that this problem only occurs in Chrome. Could it be a browser issue rather than a coding problem? I'm working on creating a circle with clickable sections using HTML5 Canvas. The circle itself ...

Guide on serializing an object containing a file attribute

I'm currently working on creating a small online catalog that showcases various housing projects and allows users to download related documents. The data structure I am using is fairly straightforward: each project has its own set of properties and a ...

Issues with jQuery compatibility when used alongside HTML and CSS

My coding tool is flagging errors in my JavaScript file, including: -'$' usage before definition. -Incorrect spacing between 'function' and '(' This is the content of my JS file: $(document).ready(function() { $(window).s ...

A single element containing two duplicates of identical services

I am encountering an issue with my query builder service in a component where I need to use it twice. Despite trying to inject the service twice, it seems that they just reference each other instead of functioning independently, as shown below: @Component( ...

Unable to capture the text within the span element. Attempting to retrieve a response from a previously run javascript function

Currently, I am facing a challenging task in FileMaker using Webdirect. I have implemented a QR code generator and reader, and while I can successfully read the code, I am struggling to capture the result of the scan. The scanned data is displayed in a hid ...

What is the best method to retrieve checked checkbox values and the selected dropdown value using AngularJS?

My code is set up to capture checked checkbox values and selected dropdown value when the submit button is pressed. It successfully retrieves the checked checkbox values, but I'm having trouble getting the selected offer from the dropdown. For example ...

What is the best way to adjust the size of an image to the viewing area

In my application, users can take photos either horizontally or vertically. These images are then displayed in a gallery on a webpage, and when clicked on, they expand using a Modal. My issue arises with horizontal images looking smaller than vertical one ...

Trouble with the Ngx-Captcha feature

I am currently utilizing https://www.npmjs.com/package/ngx-captcha/v/11.0.0. <ngx-recaptcha2 #captchaElem [siteKey]="'6Leh1ZIjAAAAAG8g0BuncTRT-VMjh3Y7HblZ9XSZ'" (success)="handleSuccess($event)" [useGlobalDomain]="fals ...

Strategies for transferring class attribute to child component element

Is there a way to pass the class attribute from parent to child component element in React? Check out this example: https://codesandbox.io/s/pedantic-shamir-1wuuv I want to add a class to the Component "Input Field" https://i.sstatic.net/yphxk.png My go ...

Is there a way to access the body html element within a template in vue.js?

I'm struggling to add styles to the body element of my HTML page. It seems like I can't access it directly from the template because there's another body element nested inside the main body. Even when I try to change the style using JavaScri ...

Error: SQLite database file name must be specified

I'm currently working through this tutorial that guides us in building an app with next.js. The tutorial involves using sqlite and performing database testing. One of the key components of the tutorial is the 'database-test.js' file: cons ...

Organizing Vue Components in Laravel Without Single Page Application Approach: Best Practices for Separate File Structure for Each Page

I have a Laravel Vue application that is not a single page application (SPA), so I am still using Laravel blades to separate the pages. Each page imports app.js, which is compiled by webpack and contains all my Vue components. The issue is that app.js is b ...