Vue+Django front-end and back-end interaction cross-domain (Xiaobai)

Vue+Django front-end and back-end development

When we develop using Vue and Django from scratch, we will encounter cross-domain problems. Generally speaking, the local port of Vue can be 8080 or other, and the local port of Django is generally 8000.
Although in Vue we use axios to send http requests to port 8000, we still receive restrictions on cross-domain access.
Here we explain how to configure it from the front and back ends to solve cross-domain problems.

Front-end Vue configuration

1. config/index.js

Cross-domain based on encapsulated axios
In the front-end config/index.js, set proxy for cross-domain


module.exports = {
    
    
    devServer:{
    
    
      proxy:{
    
    
        '/api':{
    
    //表示拦截以/api开头的请求路径
          target:'http://127.0.0.1:8000',
          changOrigin: true,//是否开启跨域
          pathRewrite:{
    
    
            '^/api':'' //重写api,把api变成空字符,因为我们真正请求的路径是没有api的
          }
        }
      }
    }
}

2. axios package file

Create a json file, and when encapsulating axios.create, set its baseURL to api, as shown below

const http = axios.create({
    
    
  baseURL: '/api',
  timeout: 50000
})

Backend Django configuration

1. Install the django-cors-headers library

Install directly with pip install in python environment

2. Set the setting.py file

In setting.py, add the APP required for cross-domain in INSTALLED_APPS corsheaders, also add the response middleware in MIDDLEWARE, and set the request method that allows cross-domain requests to ALL

INSTALLED_APPS = [
    ......
    'corsheaders',
    ......
]

MIDDLEWARE = [
    ......
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ......
]

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

If such settings are made on both the front and back ends, the front and back ends should be able to interact with data!

Guess you like

Origin blog.csdn.net/m0_53689197/article/details/133028451