django与vue 前后端分离开发,自测一系列设置,跨域,路由中间件

路由中间件设置:

本地设置路由是localhost:8000:

首先在vue里开始设置:

在confi文件夹下,设置dev.env.js

代码如下:

'use strict'
const merge = require( 'webpack-merge')
const prodEnv = require( './prod.env')

module. exports = merge( prodEnv, {
NODE_ENV: '"development"',
API_HOST: '"http://localhost:8000"' // 开发环境接口地址(这里是增加的内容)
})

然后在index.js下:

proxyTable: {
'/api' : {
target: 'http://localhost:8000/', //代理接口
changeOrigin: true, //允许跨域
pathRewrite: {
'^/api' : ''
}
}
}
最后在prod.env.js下:
'use strict'
module. exports = {
NODE_ENV: '"production"',
API_HOST: '"http://localhost:8000"' // 正式环境接口地址(这里是增加的内容)
}

接下来就是跨域问题了:

在vue里设置:

首先在main.js里设置:

import Axios from 'axios'
Vue. prototype. $http = Axios

再就是在子组件里设置了:

import qs from 'qs'
this. $http. post( '/api/loginss/', qs. stringify( datas),
 {
        headers: {
           'Content-Type' : 'application/x-www-form-urlencoded',
      }
      }
)

用post请求写这种格式

然后就是在django设置了:

主要是在settings.py里面设置:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'corsheaders', #添加这行
'django.contrib.messages',
'django.contrib.staticfiles',
'ceshrapp'
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware', # 添加这行,注意顺序
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

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',
)

按照我的做 你会成功的

猜你喜欢

转载自blog.csdn.net/guan__ye/article/details/80694803