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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM