前端(1) post
methods:{
doLogin:function(){
this.username
this.password
this.$axios.request({
url:'http://127.0.0.1:8000/api/v1/auth/',
method:'POST',
data:{
user:this.username,
pwd:this.password
},
headers:{
'Content-Type':'application/json'
}
}).then(function(arg){
console.log(arg)
}).catch(function(arg){
console.log(发生错误)
})
}
}
前端(2) put
methods:{
doLogin:function(){
this.username
this.password
this.$axios.request({
url:'http://127.0.0.1:8000/api/v1/auth/',
method:'PUT',
data:{
user:this.username,
pwd:this.password
},
headers:{
'Content-Type':'application/json'
}
}).then(function(arg){
console.log(arg)
}).catch(function(arg){
console.log(发生错误)
})
}
}
后端(1)
from rest_framework.views import APIView
from rest_framework.response import Response
class AuthView(APIView):
def options(self, request, *args, **kwargs):
# 进行预检
obj = Response('')
obj['Access-Control-Allow-Origin'] = '*'
obj['Access-Control-Allow-Headers '] = 'Content-Type'
obj['Access-Control-Allow-Methods '] = 'PUT,POST,DELETE'
return obj
def post(self,request,*args,**kwargs):
obj = Response('')
obj['Access-Control-Allow-Origin'] = '*'
return obj
后端(2)
中间件
from django.utils.deprecation import MiddlewareMixin
class Alloriven(MiddlewareMixin):
def process_response(self, request, response):
response['Access-Control-Allow-Origin'] = '*'
if request.method == 'OPTIONS':
# 我只响应你 content-type 如果你定义了其他的头,浏览器就不会返回给你数据
response['Access-Control-Allow-Headers '] = 'Content-Type'
# 如果是put 或者是delete请求就需要 加方法响应
response['Access-Control-Allow-Methods '] = 'PUT,DELETE'
return response