一、跨域

    浏览器的同源策略

                ----对ajax请求进行阻拦

                ----对href属性读不阻拦

       xhr=new XMLHttpRequest

       xhr.open...

       xhr.send(...)

   解决方案:

       ---JSONP

                 点击按钮: 

                        动态添加一个

<script src='http://www.baidu.com/users/'></script>
<script>
function func(arg){
alert(arg)
}
</script

删除

<script src='http://www.baidu.com/users/'></script>

二、CORS

客户端浏览器:

--$.ajax()

a. 简单请求(非常好)

A网站:
<input type="button" value="获取用户数据" onclick="getUsers()">

<script src="jquery-1.12.4.min.js"></script>
<script>
function getUsers() {
$.ajax({
url: 'http://127.0.0.1:8000/users/',
type:'GET',
success:function (ret) {
console.log(ret)
}
})
}
</script>

服务商:
class UsersView(views.APIView):
def get(self,request,*args,**kwargs):

ret = {
'code':1000,
'data':'老男孩'
}
response = JsonResponse(ret)
response['Access-Control-Allow-Origin'] = "*"
return response

b. 复杂请求(性能上的损耗,options预检,真实的请求)
A网站:
<input type="button" value="获取用户数据" onclick="getUsers()">

<script src="jquery-1.12.4.min.js"></script>
<script>
function getUsers() {
$.ajax({
url: 'http://127.0.0.1:8000/users/',
type:'POST',
data: {'k1':'v1'},
headers:{
'h1':'asdfasdfasdf'
},
success:function (ret) {
console.log(ret)
}
})
}
</script>

服务商:

class UsersView(views.APIView):
def get(self,request,*args,**kwargs):

ret = {
'code':1000,
'data':'老男孩'
}
response = JsonResponse(ret)
response['Access-Control-Allow-Origin'] = "*"
return response

def post(self,request,*args,**kwargs):
print(request.POST)
ret = {
'code':1000,
'data':'老男孩'
}
response = JsonResponse(ret)
response['Access-Control-Allow-Origin'] = "*"
return response

def options(self, request, *args, **kwargs):
# self.set_header('Access-Control-Allow-Origin', "http://www.xxx.com")
# self.set_header('Access-Control-Allow-Headers', "k1,k2")
# self.set_header('Access-Control-Allow-Methods', "PUT,DELETE")
# self.set_header('Access-Control-Max-Age', 10)

response = HttpResponse()
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'h1'
# response['Access-Control-Allow-Methods'] = 'PUT'
return response

2. Vue+rest示例

前端:vue
修改源:
npm config set registry https://registry.npm.taobao.org

创建脚手架:
vue init webpack Vue项目名称
# Install vue-router? Yes

插件:
axios,发送Ajax请求
vuex,保存所有组件共用的变量
vue-cookies,操作cookie

流程:
1. 创建脚手架

2.
# 用于点击查看组件
<router-link to="/index">首页</router-link>

# 组件显示的位置
<router-view/>

3. 写路由
import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/components/Index'
import Login from '@/components/Login'
import Course from '@/components/Course'
import Micro from '@/components/Micro'
import News from '@/components/News'
import CourseDetail from '@/components/CourseDetail'
import NotFound from '@/components/NotFound'

Vue.use(Router)

export default new Router({
routes: [
{
path: '/',
name: 'index',
component: Index
},
{
path: '/index',
name: 'index',
component: Index
},
{
path: '/course',
name: 'course',
component: Course
},
{
path: '/course-detail/:id/',
name: 'courseDetail',
component: CourseDetail
},
{
path: '/micro',
name: 'micro',
component: Micro
},
{
path: '/news',
name: 'news',
component: News
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '*',
component: NotFound
}
],
mode: 'history'
})

4. 写组件
<template>

<div>
<h1>登录页面</h1>
<div>
<input type="text" v-model="username" placeholder="用户名">
<input type="text" v-model="password" placeholder="密码">
<a @click="doLogin">提交</a>
</div>
</div>
</template>

<script>

export default {
# 定义局部字段
data () {
return {
username: '',
password: ''
}
},
# 加载时执行
mounted:function(){
},
# 定义局部方法
methods:{
doLogin() {
var that = this
this.$axios.request({
url: 'http://127.0.0.1:8000/login/',
method: 'POST',
data: {
username: this.username,
password: this.password
},
responseType: 'json'
}).then(function (response) {
console.log(response.data)
// 找到全局变量,把用户名和token赋值到其中。
that.$store.commit('saveToken',response.data)
// 重定向到index
that.$router.push('/index')
})
}
}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

5. ajax请求:axios
npm install axios

main.js
import Vue from 'vue'
import App from './App'
import router from './router'

import axios from 'axios'

Vue.prototype.$axios = axios

Vue.config.productionTip = false
...

组件使用:
this.$axios.request({
url: 'http://127.0.0.1:8000/login/',
method: 'POST',
data: {
username: this.username,
password: this.password
},
responseType: 'json'
}).then(function (response) {
console.log(response.data)

that.$router.push('/index')
})

PS:重定向 that.$router.push('/index')

6. vuex
npm install vuex

main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'

import store from './store/store' # vuex

Vue.prototype.$axios = axios

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
el: '#app',
store, # vuex
router,
components: { App },
template: '<App/>'
})

src/store/store.js
import Vue from 'vue'
import Vuex from 'vuex'
import Cookie from 'vue-cookies'

Vue.use(Vuex)

export default new Vuex.Store({
// 组件中通过 this.$store.state.username 调用
state: {
username: Cookie.get('username'),
token: Cookie.get('token')
},
mutations: {
// 组件中通过 this.$store.commit(参数) 调用
saveToken: function (state, data) {
state.username = data.username
state.token = data.token
Cookie.set('username', data.username, '20min')
Cookie.set('token', data.token, '20min')

},
clearToken: function (state) {
state.username = null
state.token = null
Cookie.remove('username')
Cookie.remove('token')
}
}
})

7. vue-cookies
npm install vue-cookies

Cookie.get('username')

Cookie.set('username', data.username, '20min')
Cookie.remove('username')

src/store/store.js
import Vue from 'vue'
import Vuex from 'vuex'
import Cookie from 'vue-cookies' # vue-cookies

Vue.use(Vuex)

export default new Vuex.Store({
// 组件中通过 this.$store.state.username 调用
state: {
username: Cookie.get('username'), # vue-cookies
token: Cookie.get('token') # vue-cookies
},
mutations: {
// 组件中通过 this.$store.commit(参数) 调用
saveToken: function (state, data) {
state.username = data.username
state.token = data.token
Cookie.set('username', data.username, '20min') # vue-cookies
Cookie.set('token', data.token, '20min')

},
clearToken: function (state) {
state.username = null
state.token = null
Cookie.remove('username') # vue-cookies
Cookie.remove('token')
}
}
})

8. 路由
# 定义路由
{
path: '/course-detail/:id/',
name: 'courseDetail',
component: CourseDetail
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '*',
component: NotFound
}

# router-link参数
<router-link :to="{'path':'/course-detail/'+item.id }">{{item.name}}</router-link>
<router-link to="/index">首页</router-link>

# 获取传过来的参数
this.$route.params.id
# 重定向
this.$router.push('/index')

 

python 之CORS,VUE+rest_framework示例的更多相关文章

  1. C++开发python windows版本的扩展模块示例

    C++开发python windows版本的扩展模块示例 测试环境介绍和准备 测试环境: 操作系统:windows10 Python版本:3.7.0 VS版本:vs2015社区版(免费) 相关工具下载 ...

  2. Vue 1-- ES6 快速入门、vue的基本语法、vue应用示例,vue基础语法

    一.ES6快速入门 let和const let ES6新增了let命令,用于声明变量.其用法类似var,但是声明的变量只在let命令所在的代码块内有效. { let x = 10; var y = 2 ...

  3. Vue(1)- es6的语法、vue的基本语法、vue应用示例,vue基础语法

    一.es6的语法 1.let与var的区别 ES6 新增了let命令,用来声明变量.它的用法类似于var(ES5),但是所声明的变量,只在let命令所在的代码块内有效.如下代码: { let a = ...

  4. python中hashlib模块用法示例

    python中hashlib模块用法示例 我们以前介绍过一篇Python加密的文章:Python 加密的实例详解.今天我们看看python中hashlib模块用法示例,具体如下. hashlib ha ...

  5. Python自定义线程类简单示例

    Python自定义线程类简单示例 这篇文章主要介绍了Python自定义线程类,结合简单实例形式分析Python线程的定义与调用相关操作技巧,需要的朋友可以参考下.具体如下: 一. 代码     # - ...

  6. python golang中grpc 使用示例代码详解

    python 1.使用前准备,安装这三个库 pip install grpcio pip install protobuf pip install grpcio_tools 2.建立一个proto文件 ...

  7. Vue+restfulframework示例

    一.简单回顾vue 前不久我们已经了解了vue前端框架,所以现在强调几点: 修改源: npm config set registry https://registry.npm.taobao.org 创 ...

  8. Django rest framework + Vue简单示例

    构建vue项目参考这篇文章https://segmentfault.com/a/1190000008049815 一.创建Vue项目 修改源:npm config set registry https ...

  9. 支持Ajax跨域访问ASP.NET Web Api 2(Cors)的简单示例教程演示

    随着深入使用ASP.NET Web Api,我们可能会在项目中考虑将前端的业务分得更细.比如前端项目使用Angularjs的框架来做UI,而数据则由另一个Web Api 的网站项目来支撑.注意,这里是 ...

随机推荐

  1. 《从零开始学Swift》学习笔记(Day 29)——访问级别

    Swift 2.0学习笔记(Day 29)——访问级别 原创文章,欢迎转载.转载请注明:关东升的博客 访问级别: Swift提供了3种不同访问级别,对应的访问修饰符为:public.internal和 ...

  2. 问题:Unable to find a 'userdata.img' file for ABI armeabi to copy into the AVD folder.

    创建AVD时,发现创建不成功,报错“Unable to find a 'userdata.img' file for ABIarmeabi to copy into the AVD folder.” ...

  3. python函数回顾:help()

    描述 help() 函数用于查看函数或模块用途的详细说明. 语法 help 语法: help([object]) 参数说明: object -- 对象: 返回值 返回对象帮助信息. 实例 以下实例展示 ...

  4. python面向对象(二)

    属性查找 类有两种属性:数据属性和函数属性 1. 类的数据属性是所有对象共享的 2. 类的函数属性是绑定给对象用的 class BeijingStudent:   school='Beijing'  ...

  5. 使用Kotlin开发Android应用(I):简介

    Kotlin是一门基于JVM的编程语言,它正成长为Android开发中用于替代Java语言的继承者.Java是世界上使用最多的编程语言之一,当其他编程语言为更加便于开发者使用而不断进化时,Java并没 ...

  6. ACM解题之回文序列

    题意: 一个长度为 n 的序列 a1, m2, ..., an-1, an,如果 ai = an-i+1, i = 1, 2, ..., n,则称之为"回文序列".本题对于给定的一 ...

  7. [转]c#中从string数组转换到int数组

    string[] input = { "1", "2", "3", "4", "5", " ...

  8. Linux进程优先级查看及修改

    进程cpu资源分配就是指进程的优先权(priority).优先权高的进程有优先执行权利.配置进程优先权对多任务环境的Linux很有用,可以改善系统性能.还可以把进程运行到指定的CPU上,这样一来,把不 ...

  9. UI控件之UITabBarController

    UITabBarController:标签栏控制器,继承自UIViewController,用标签栏的形式管理视图控制器,各标签栏对应的视图控制器之间相互独立,互不影响,单击标签栏,显示标签栏对应的视 ...

  10. Python编程-多道技术和进程

    一.多道技术 1.多路复用 操作系统主要使用来 记录哪个程序使用什么资源 对资源请求进行分配 为不同的程序和用户调解互相冲突的资源请求. 我们可将上述操作系统的功能总结为: 处理来自多个程序发起的多个 ...