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

相关推荐
用户8356290780511 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon2 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly2 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程2 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly4 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风11 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风11 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风1 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风1 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python