django中template中post请求接口csrf问题

bash 复制代码
$(function () {
  $.ajaxSetup({
    headers: { "X-CSRFToken": getCookie("csrftoken") }
  });
});
 
 
// 为防止CSRF(Cross-site request forgery)跨站请求伪造,发post请求时需要在cookie中创建随机码
function getCookie(name)
{
 var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
 /*
   上面这句话相当于:
 var arr;
 var reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
  */
 if(arr=document.cookie.match(reg))
   return decodeURI(arr[2]);  //ECMAScript v3 已从标准中删除了 unescape() 函数,并反对使用它,
                 // 因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。
 else
   return null;
}

参考:

https://www.jb51.net/article/182658.htm?tdsourcetag=s_pcqq_aiomsg

https://blog.csdn.net/qq_41909967/article/details/85058703

相关推荐
Rookie_JE12 分钟前
python docxtpl库学习
python
我不是小upper13 分钟前
CNN+BiLSTM !!最强序列建模组合!!!
人工智能·python·深度学习·神经网络·cnn
锐学AI20 分钟前
从零开始学MCP(四)- 认识MCP clients
人工智能·python
爱打代码的小林40 分钟前
python基础(pandas库)
服务器·python·pandas
shenzhenNBA42 分钟前
如何在python文件中使用日志功能?简单版本
java·前端·python·日志·log
编织幻境的妖1 小时前
Python垃圾回收机制详解
开发语言·python
李剑一1 小时前
Python学习笔记4
python
listhi5202 小时前
MOEAD算法实现详解(基于Python与MATLAB)
python·算法·matlab