Django2.0 解决VUE的跨域请求问题

1.VUE上的请求:

安装qs: npm install qs --save

请求:

      var qs = require('qs')
      this.form.user = localStorage.getItem('loginname')
      console.log('***********')
      console.log(qs.stringify(this.form))
      // this.form的值:user=editor&phone1=&phone2=&messagenameen=&messagenamezh=&groupid=
      axios.post('http://localhost:8000' + '/usersmanage/getpersoninfo/', qs.stringify(this.form),
        {
          headers:
            {
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then((response) => {
        if (response.status === 'success') {
          console.log('yesyesyes')
        } else {
          this.$message({
            message: '获取个人信息失败!',
            type: 'error'
          })
        }

        this.dialogFormVisible = false
      }).catch(function(error) {
        console.log(error)
      })

2. Django上安装django-cors-headers 解决跨域请求问题

pip3 install django-cors-headers

然后配置:在settings.py中

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
     #……
    'corsheaders',
]

MIDDLEWARE = [
    # ……
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

# 解决跨域请求问题
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = ()  #空白表示任意

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值