返回顶部

csrf在Vue中的应用

  • 前端Vue
  • 后端Django
  • 如何使用csrf?
    • 后端Django在settings.py中将注释掉的csrf中间件取消注释(如果之前注释过)
    • 'django.middleware.csrf.CsrfViewMiddleware',
    • 前端Vue的main.js中加上如下代码:
      import Axios from 'axios'
      
      let getCookie = function (cookie) {
          let reg = /csrftoken=([\w]+)[;]?/g
          return reg.exec(cookie)[1]
      
      }
      
      Axios.interceptors.request.use(
        function(config) {
          // 在post请求前统一添加X-CSRFToken的header信息
          let cookie = document.cookie;
          if(cookie && config.method == 'post'){
            config.headers['X-CSRFToken'] = getCookie(cookie);
          }
          return config;
        },
        function(error) {
          // Do something with request error
          return Promise.reject(error);
        });

       

    • 上面代码知识针对于post请求,如果是所有请求,那就多写几个if语句。
  • 非专业前端,自己总结的方法
  • 参考:https://www.cnblogs.com/horns/p/11077458.html
posted @ 2020-08-10 12:21  DCooo  阅读(2920)  评论(0编辑  收藏  举报