django和vue通信小测试
提示:以下是本篇文章正文内容,下面案例可供参考
一、跨域问题
1.同源策略
同源是指两个网页具有相同的协议、主机和端口号,如果两个网页不满足同源条件,他们就属于不同的源,同源策略将应用。同源策略是一种安全机制,用于保护用户信息和防止恶意代码的执行,限制了不同源的网页之间的交互。
前后端分离的情况下,两个网页的端口号不同,不是同源,出于同源策略的限制就会产生跨域问题。
2.后端解决跨域问题
1.Django框架中通过django-core-headers解决,安装
pip install django-cors-headers
2.注册到settings.py文件中的 INSTALLED_APPS中
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'app01.apps.App01Config'
]
3.添加到 MIDDLEWARE中
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
4. settings.py末加上
#允许携带cooki
CORS_ALLOW_CREDENTIALS = True
#增加跨域忽略
CORS_ORIGIN_ALLOW_ALL = True
# 允许所有方法
CORS_ALLOW_METHODS = ('*')
# 允许所有请求头
CORS_ALLOW_HEADERS = ('*')
#前端端口号
CORS_ORIGIN_WHITELIST = (
'http://localhost:5173',
)
二、小测试
1.前端
代码如下(示例):
<template>
<div class="test">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="changeage">get</button>
<button @click="changeage1">post</button>
</div>
</template>
<script lang="ts" setup name="Test">
import {ref} from 'vue'
import axios from 'axios'
let name=ref('张三')
let age=ref(18)
function changeage(){
axios.get(
'/changeage/'
).then(response =>{
age.value=response.data['age']
console.log(age.value)
}
)
}
function changeage1(){
let formdata= new FormData()
formdata.append('age',21)
axios.post(
'/changeage/',
formdata,
{headers:{'Content-Type':'multipart/form-data'}, }
).then(response =>{
age.value=response.data['age']
console.log(age.value)
}
).catch(error =>{
console.log(6)
}
)
}
</script>
<style>
.test{
text-align: center;
}
</style>
axios.get('url ')
axios.post('url ',
FormData,
{headers:{ }}
)
2.后端
代码如下(示例):
from django.shortcuts import render
from django.http import JsonResponse
# Create your views here.
def changeage(request):
response = {}
response['age'] = 20
if request.method == 'POST':
if len(request.POST['age']) > 0:
response['age'] = request.POST.get('age')
return JsonResponse(response)
三、axios
1.官方文档
起步 | Axios中文文档 | Axios中文网 (axios-http.cn)
npm install axios
基本使用
。。。