django使用fetch提交post跨域与cors防护最终方案

假设前端输入两个数,计算两数和后返回。
1.前端模板代码
添加 {%csrf_token%}例如:


{%csrf_token%}
<input id=”val1″ type=”text” />
<input id=”val2″ type=”text” />
<button type=”button”>测试</button>

2.js代码

<script type=”text/javascript”>
function btn(){
let val1=document.getElementById(‘val1’).value;
let val2=document.getElementById(‘val2′).value;
let token='{{csrf_token}}’;
let url=”/test/”;
let data=JSON.stringify({
‘val1’:val1,
‘val2’:val2
});
let opt={
method: ‘POST’,
mode:’cors’,
credentials:’include’,
body:data,
headers: new Headers({
“X-csrftoken”:token, //这里向服务端传送crsf字段
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’
})
};
fetch(url,opt)
.then(res=>res.json())
.then(res=>{console.log(res))
.catch(err=>{console.log(err)})
}
</script>

3.服务端views.py代码,设置响应头
from django.http import JsonResponse
def setHeader(res):
response = JsonResponse(res)
response[“Access-Control-Allow-Headers”] = “content-type”
response[“Access-Control-Allow-Origin”] = “*”
response[“Access-Control-Allow-Methods”] = “POST, GET, OPTIONS”
response[“Access-Control-Max-Age”] = “1000”
return response

def test(request):
postBody=request.body
res=json.loads(postBody)
#此处res经序列号后为字典对象
res1=res[‘val1’]
res2=res[‘val2’]
sum=res1+res2
obj={‘sum’:sum}
return setHeader(obj)

发表评论

电子邮件地址不会被公开。