Django前后端分离跨域设置

1.安装Django-cors-headers

pip install django-cors-headers

2.配置跨域

settings代码

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "corsheaders",  # 跨域设置第一步:跨域支持,一定要放在需要跨域请求的app前面
    # 子应用配置
    'case',
]
....
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # 跨域设置第一步:务必写在CommonMiddleware的上方
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
....
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# 跨域设置第三步骤:跨域设置
CORS_ALLOW_CREDENTIALS = True  # 解决跨域
CORS_ORIGIN_ALLOW_ALL = True  # 解决跨域

# 跨域设置第三步骤:允许的请求头,不能用*,要写具体的请求头,不然Vue会跨域失败,在这里坑了我好久好久MD
CORS_ALLOW_HEADERS = (
    'x-requested-with',
    'content-type',
    'accept',
    'origin',
    'authorization',
    'x-csrftoken'
)

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

3.vue中安装axios

npm install axios
npm install vue-axios

4.配置axios

进入vue中的main.js,配置axios

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import {Axios} from "axios";
import VueAxios from "vue-axios";
const app=createApp(App)

app.use(router,Axios,VueAxios).mount('#app')

5.在vue中使用axios

随便一个点击事件的请求:

import axios from 'axios'

const clickhander = () => {
  axios.get(`http://127.0.0.1:8000/api/v1/user/`).then((response)=>{
    console.log(response.data)
  }).catch((error)=>{
    console.log(error)
  })
}

此时就会向后端发送请求,得到最终的结果.
其他的请求可以参考axios官网

6.axios的封装使用

一般在发送请求的时候,需要设置请求头,请求的信息需要过滤处理,因此可以将这些方法全部封装到一起.
在vue项目的src路径下创建一个http文件夹,创建一个index.js文件封装这些代码:
在这里插入图片描述
代码如下:

import axios from "axios";
//axios.create  创建一个axios实例 我们给这个实例编写配置,后续所有通过实例发送的请求,都受当前配置约束
const $http = axios.create({
    baseURL: 'http://127.0.0.1:8000/api/',
    timeout: 5000,
    // headers: {'X-Custom-Header': 'foobar'}
});


// 添加请求拦截器
$http.interceptors.request.use(function (config) {
    //发送前可以携带请求头,通过方法获取
    // config.headers.token = ''


    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
$http.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么,响应我们最关心的就是返回的数据,因此可以对其他数据进行拦截
    let data=response.data
    return data;
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
});

export default $http

一定要注意请求头中的信息,根据需求写,否则会出错,坑死我了

7.使用封装的axios

注意url中的引号是反引号,键盘最左上角的一个键

import $http from "../http/index"

const clickhander = () => {
  $http.get('http://127.0.0.1:8000/api/v1/user/').then(function (response) {
    console.log(response);
  }).catch((error) => {
    console.log(error);
  });
}

甚至可以单独创建一个js文件,将某一类的需求的请求全部封装起来调用,比如user的请求,就全部放到user中:
user.js

import $http from './index.js'

export const getData=$http.get(`http://127.0.0.1:8000/api/v1/user/`)

然后在vue文件中直接调用就可以了,等到以后要修改其他路径名的时候,就可以直接进行修改,不需要再到某个页面中进行修改了.
vue中调用:

import {getData} from "@/http/user";
//处理登入
const clickhander = () => {
  getData.then(function (response) {
    console.log(response);
  }).catch((error) => {
    console.log(error);
  });
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值