码迷,mamicode.com
首页 > 移动开发 > 详细

axios通过django的csrf验证

时间:2018-07-04 21:36:57      阅读:470      评论:0      收藏:0      [点我收藏+]

标签:requested   http   代码   ret   axios   ade   word   style   reg   

django会在浏览器的cookie里面保存一项csrftoken=GvzB3ilhlgadishmascacsilreclherlkjhaklsdv3qx4M96XRG88omScDPQaKoMxJ;

这个是从django生成的,django会检查每个http请求的headers 里面的  X-CSRFToken 项的值是否和cookie里面保存的值相同,如果不相同或者缺失,就拒绝这个请求,如果相同,说明这次请求是从真实用户发起的。

所以要做的就是在每次请求的 headers 里面加上X-CSRFToken:csrftoken值

axios的配置代码如下:

                //添加请求拦截器,在发送请求前拦截,对请求进行操作
                this.$http.interceptors.request.use((config) => {
                    config.headers[‘X-Requested-With‘] = ‘XMLHttpRequest‘;
                    let regex = /.*csrftoken=([^;.]*).*$/; // 用于从cookie中匹配 csrftoken值
                    config.headers[‘X-CSRFToken‘] = document.cookie.match(regex) === null ? null : document.cookie.match(regex)[1];
                    return config
                });
                // 发送 POST 请求
                this.$http({
                    method: ‘post‘,
                    url: ‘http://127.0.0.1:8000/user/‘,
                    data: {
                        username: ‘abc123‘,
                        password: ‘abc123‘
                    }
                });

 

axios通过django的csrf验证

标签:requested   http   代码   ret   axios   ade   word   style   reg   

原文地址:https://www.cnblogs.com/weihengblog/p/9265357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!