Strategies for managing the net::ERR_CONNECTION_REFUSED error when using Axios in a Vue.js and Django environment

I'm encountering issues with Axios while trying to send data to the backend. What steps should I take?

Within the

.then(response => { this.$router.push('/Log-in') return response })
section, I returned the "response" because an error message in the console indicated that 'response' is defined but never used.

This is a snippet from my vue.js file:

import axios from 'axios'
if (!this.errors.length) {
  const formData = {
    username: this.username,
    password: this.password,
    email: this.email
  }

  axios
    .post('/api/v1/users', formData)
    .then(response => {
      this.$router.push('/Log-in')
      return response
    })
    .catch(error => {
      if (error.response) {
        for (const property in error.response.data) {
          this.errors.push(`${property}: ${error.response.data[property]}`)
        }

        console.log(JSON.stringify(error.response.data));
      } else if (error.massege) {
        this.errors.push('Something went wrong, Please try again!')
        console.log(JSON.stringify(error));
      }
    })
}

Here's the CORS configuration in my settings.py file for Django:

CORS_ALLOWED_ORIGINS = [
'http://localhost:8000',
'http://127.0.0.1:8000/'
]

Answer №1

I faced a similar issue and was able to resolve it successfully. Here's the solution I implemented:

  1. To fix the problem, start by installing django-cors-headers using the command below in your terminal:
pip install django-cors-headers
  1. Next, you need to add the following code snippet to your settings.py file:
MIDDLEWARE = [
   ...,
   "corsheaders.middleware.CorsMiddleware",
   "django.middleware.common.CommonMiddleware",
]

CORS_ORIGIN_WHITELIST = [
   'http://localhost:8000',
   'http://127.0.0.1:8000/'
]

If this doesn't resolve the issue, proceed to step 3:

  1. In your settings.py file, make sure to include the following:
INSTALLED_APPS = [
   ...,
   "corsheader"
   ...,
]

Referencing the documentation of django-cors-headers version 3.14.0:

The purpose of django-cors-headers is to allow cross-origin requests to your Django application from various sources.

For additional information about this package, visit: https://pypi.org/project/django-cors-headers/

I trust this guidance proves beneficial in resolving your issue.

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

Determine the length of the array and come up with a unique line of code

Below is the code snippet I am currently working on: const json = `{"BTC":{"available":0.00024868,"onOrder":0,"btcValue":0.00024868,"btcTotal":0.00024868},"LTC":{"available":0,"onOr ...

Switch between active tabs (Typescript)

I am working with an array of tabs and here is the code snippet: const navTabs: ITab[] = [ { Name: allTab, Icon: 'gs-all', Selected: true }, { Name: sources.corporateResources, Icon: 'gs-resources', Selected: false }, { Name ...

Unable to obtain the identification number of the specified variable

I am working on a jquery event that is enclosed within $(document).ready(function() { //.....// });. The code for the event is as follows: $('.puzzle_cells').keyup(function(event) { }); My next step is to retrieve the ID of the <input> e ...

`Arc canvas countdown timer`

My countdown timer created using canvas is functioning well, but I am encountering some issues: I would like to align the circle representing seconds with the circles for minutes, hours, and days similar to this demo. Please ensure running the code snipp ...

Please phone back regarding the adjustment of column sizes

Are there any callbacks provided for column resizing in ag-Grid? I was unable to locate any documentation related to column resize callbacks. Here is a sample code snippet: var onColumnResized = function(params){ console.log(params); }; gridOptions.onC ...

spinning div content in a manner reminiscent of a roulette wheel

I am looking to create a roulette game that randomly selects numbers and displays them. Initially, I attempted to use images and backgroundOffset, but it caused significant lagging issues and difficulty in checking the rolled number. Therefore, I have impl ...

Encountering a Typescript error when attempting to access the 'submitter' property on type 'Event' in order to retrieve a value in a |REACT| application

I am facing an issue with my React form that contains two submit buttons which need to hit different endpoints using Axios. When I attempt to retrieve the value of the form submitter (to determine which endpoint to target), I encounter an error while work ...

What is more costly in terms of performance: toggling the visibility of a DOM node or adding/removing a DOM node?

When it comes to calling, which is the more costly operation? Displaying and hiding a DOM node Creating and deleting DOM nodes Let's assume we only have one or a few (less than 5) nodes that require manipulation, and the application is running on a ...

Storing data in an object or array using Node.js to improve caching efficiency

I'm attempting to store and retrieve information in a node CLI script using either an array or an object. My goal is to have a simple key-value setup where I can fetch usernames by using the ID as the key. The code snippet below shows my attempt, but ...

Acquiring the index of a selector event within a list of dynamic elements

I am seeking guidance on how to go about solving the issue of obtaining an event index. I have a hunch that closures might play a role in the solution and would appreciate some insights. Initially, I dynamically build an HTML5 video container using an aja ...

Utilizing HTML5 history instead of hash URLs to preserve the user's browsing history

Our application is a single page that dynamically loads results based on query strings. The query string format we use is as follows: ?city=Delhi&pn=1 Within the SPA, there are different sections displayed on the same page. As users navigate through ...

Is there a method within the jQuery Form plugin to display a new page upon successful completion of an Ajax request?

After a user uploads a photo, it goes through a controller (profile/upload_picture) for validation of file type and size. If there are validation errors, they will be displayed using Ajax on the frontend. This functionality is working smoothly. However, ...

Retrieve an array of specific column values from an array of objects using Typescript

How can I extract an array from an array of objects? Data var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, ...

What is the best way to send a variable from an axios get request to a sub-component in Vue.js?

Here is how I make an axios get request: index() { axios.get('/list/items').then(response => { this.items = response.data.items; this.stats = response.data.stats; } When I do console.log(this.stats), it correctly displays th ...

The res.download() function is not functioning properly when called from within a function, yet it works perfectly when directly called through the API in a browser

I have a button that, when clicked, triggers the downloadFile function which contacts the backend to download a file. async downloadFile(name) { await this.$axios.$get(process.env.API_LINK + '/api/files/' + name) }, app.get('/api/files/ ...

Is there a way to get rid of this awful hover effect on this button?

My friend and I have been developing a Chrome extension for the Roblox Devforum with some initial success. We started working on it yesterday, and already have our button placed in the header similar to extensions like Roblox+ or RoPro. However, we encoun ...

Tips for calculating the total value of a nested array

I seem to be facing a slight logic issue at the moment. Currently, I have an accordion with images taken https://i.sstatic.net/UUs8Y.png In the HTML, you'll find headers for LIVE BETTING, MLB, MLB Props, and NBA (which is just a snippet of a list c ...

a reactjs beforeunload event listener was added but not properly removed

I am working on a React component that looks like this: import React, { PropTypes, Component } from 'react' class MyComponent extends Component { componentDidMount() { window.addEventListener("beforeunload", function (event) { ...

Exploring the passing of parameters in Angular JS getters

In my Angular 1.6.x project, I have a collection of checkboxes that store their state in a variable called selectedJobIds. This variable contains the ids of selected jobs along with their corresponding true or false values: $scope.selectedJobIds = { 23: ...

The Json object's size increases exponentially with each subsequent return

There seems to be a strange issue with the PHP file that is causing the JSON objects to duplicate. The first time I run the script, I receive 5 rows, which matches the number of rows in the table. However, on the second run, I get double the results. Wha ...