Vue + Django 配置跨域
"""
我这里使用的vue-element-ui + Django
配置Vue / 配置django 实现一个post请求 登陆功能
"""
配置Django
# 下载安装包 pip install django-cors-headers #django settings INSTALLED_APPS = [ 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ]
设置白名单 更具自己的需求, 不设置也没有关系 CORS_ORIGIN_WHITELIST =( 'http:xxx.xxx.xxx.xx:xxx' )
CORS_ALLOW_CREDENTIALS = True # 允许携带cookie
配置Vue
# /config/index.js
proxyTable: {
'/api': {
target: 'http://xxx.xx.xx.xx:xxxx', // 你请求的第三方接口
changeOrigin: true,
pathRewrite: { // 路径重写,
'^/api': '/api' }
}
},
写vue 写一个登陆页面 login.vue
# src/views/login.vue
<template> <div class="login-wrap"> <el-form label-position="left" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm login-container"> <h3 class="title">用户登录</h3> <el-form-item prop="username"> <el-input type="text" v-model="ruleForm.username" auto-complete="off" placeholder="账号"></el-input> </el-form-item> <el-form-item prop="password"> <el-input type="password" v-model="ruleForm.password" auto-complete="off" placeholder="密码"></el-input> </el-form-item> <el-row> <el-col :span="12" class="code-box"> <img :src="ruleForm.codeimg" alt="" class="codeimg" @click="getcode()"> </el-col> </el-row> <el-checkbox class="remember" v-model="rememberpwd">记住密码</el-checkbox> <el-form-item style="width:100%;"> <el-button type="primary" style="width:100%;" @click="submitForm('ruleForm')" :loading="logining">登录</el-button> <!-- //<el-button :plain="true" @click="open">打开消息提示</el-button> --> </el-form-item> </el-form> </div> </template> <script type="text/ecmascript-6"> import { login } from '../api/User' import md5 from 'js-md5' export default { name: 'login', data() { return { //定义loading默认为false logining: false, // 记住密码 rememberpwd: false, ruleForm: { //username和password默认为空 username: '', password: '', randomStr: '', codeimg: '' }, //rules前端验证 rules: { username: [{ required: true, message: '请输入账号', trigger: 'blur' }], password: [{ required: true, message: '请输入密码', trigger: 'blur' }], } } }, // 创建完毕状态(里面是操作) created() { this.$message({ message: '账号密码不为空即可', type: 'success' }) this.getuserpwd() }, // 里面的函数只有调用才会执行 methods: { // 获取用户名密码 getuserpwd() { if (getCookie('user') != '' && getCookie('pwd') != '') { this.ruleForm.username = getCookie('user') this.ruleForm.password = getCookie('pwd') this.rememberpwd = true } }, //获取info列表 submitForm(formName) { this.$refs[formName].validate(valid => { login(this.ruleForm).then(res => { if (res.code == 200) { this.$message({ type:'success', message:'nice' }) this.$store.commit('login', 'true') this.$router.push({ path: '/goods/Good' }) } else { if(res.code == 222){ this.$message({ type:'info', message:'请输入正确的账号密码 ' }) } } }) }) }, } } </script> <style scoped> .login-wrap { box-sizing: border-box; width: 100%; height: 100%; padding-top: 10%; /* background-color: #112346; */ background-repeat: no-repeat; background-position: center right; background-size: 100%; } .login-container { border-radius: 10px; margin: 0px auto; width: 350px; padding: 30px 35px 15px 35px; background: #fff; border: 1px solid #eaeaea; text-align: left; box-shadow: 0 0 20px 2px rgba(0, 0, 0, 0.1); } .title { margin: 0px auto 40px auto; text-align: center; color: #505458; } .remember { margin: 0px 0px 35px 0px; } .code-box { text-align: right; } .codeimg { height: 40px; } </style>
# src/api/User.js
import axios from 'axios';
import { loginreq, req } from './axiosF';
// 登录接口
export const login = (params) => { return loginreq("post", "/api/login/", params) };
# src/api/axiosF.js
import axios from 'axios';
// 登录请求方法
const loginreq = (method, url, params) => {
return axios({
method: method,
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: params,
traditional: true,
transformRequest: [
function(data) {
let ret = ''
for (let it in data) {
ret +=
encodeURIComponent(it) +
'=' +
encodeURIComponent(data[it]) +
'&'
}
return ret
}
]
}).then(res => res.data);
};
// 通用公用方法
const req = (method, url, params) => {
return axios({
method: method,
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
token: localStorage.getItem('logintoken')
},
data: params,
traditional: true,
transformRequest: [
function(data) {
let ret = ''
for (let it in data) {
ret +=
encodeURIComponent(it) +
'=' +
encodeURIComponent(data[it]) +
'&'
}
return ret
}
]
}).then(res => res.data);
};
export {
loginreq,
req
}
# router/index.js
// 导入组件
import Vue from 'vue';
import Router from 'vue-router';
// 登录
import login from '@/views/login';
Vue.use(Router);
// 导出路由
export default new Router({
routes: [{
path: '/',
name: '',
component: login,
hidden: true,
meta: {
requireAuth: false
}
}, {
path: '/login',
name: '登录',
component: login,
hidden: true,
meta: {
requireAuth: false
}
}]
Django
# 创建一个django 项目 django-admin startproject [projectname] # 创建一个子应用 python manage.py startapp [AppName] INSTALLED_APPS = [ 'AppName', ] # project / urls from django.urls import path,include urlpatterns = [ # path('admin/', admin.site.urls), path("api/",include('AppName.urls')) ] # 在子应用中创建一个urls.py AppName/urls from django.urls import path from AppName import views urlpatterns = [ path("login/",views.Login.as_view()), ] # AppName / views.py
from django.http import JsonResponse,HttpResponse
from django.views import View
class Login(View): def post(self,request): username = request.POST.get("username") #print(username) password = request.POST.get("password") #print(password) if username == 'admin' and password == '222222': data = { "code": 200, "message": "登陆成功" } return JsonResponse(data) else: data = { "code": 222, "message": "账号密码错误!" } return JsonResponse(data)
## 大功告成, 希望本篇文章可以帮助大家。 可以转载 标明出处! 谢谢!