一、跨域

    浏览器的同源策略

                ----对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="获取用户数据" οnclick="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="获取用户数据" οnclick="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')

 

转载于:https://www.cnblogs.com/mengqingjian/p/8436358.html

python 之CORS,VUE+rest_framework示例相关推荐

  1. python包NiBabel对医学影像文件格式进行读写:python包NiBabel简介集示例

    python包NiBabel对医学影像文件格式进行读写:python包NiBabel简介集示例 目录 python包NiBabel对医学影像文件格式进行读写:python包NiBabel简介集示例

  2. python代码翻译-用python实现百度翻译的示例代码

    用python实现百度翻译,分享给大家,具体如下: 首先,需要简单的了解一下爬虫,尽可能简单快速的上手,其次,需要了解的是百度的API的接口,搞定这个之后,最后,按照官方给出的demo,然后写自己的一 ...

  3. python绘图实例-Python matplotlib基础绘图函数示例

    原标题:Python matplotlib基础绘图函数示例 Pyplot基础图标函数: 函数 说明 plt.plot(x,y,fmt,-) 绘制一个坐标图 plt.boxplot(data,notch ...

  4. python装饰器实例-python 装饰器的使用示例

    无参修饰 ,无参数时不需要调用 def log1(func): func() @log1 def test(): print('test:') 有参修饰 def log2(func): def inn ...

  5. python的简单编程-python入门脚本的简单示例

    编程之家收集整理的这篇文章主要介绍了python入门脚本的简单示例,编程之家小编觉得挺不错的,现在分享给大家,也给大家做个参考. 感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧. ...

  6. boost::python模块实现使用任意 Python 序列创建 ndarray 的示例

    boost::python模块实现使用任意 Python 序列创建 ndarray 的示例 实现功能 C++实现代码 实现功能 boost::python模块实现使用任意 Python 序列创建 nd ...

  7. boost::python模块实现使用内置 python 数据类型创建 ndarrays 的示例,并提取成员变量的类型和值测试程序

    boost::python模块实现使用内置 python 数据类型创建 ndarrays 的示例,并提取成员变量的类型和值测试程序 实现功能 C++实现代码 实现功能 boost::python模块实 ...

  8. vue项目示例代码git_您应该了解的5个Git命令以及代码示例

    vue项目示例代码git I've used Git for some years now, and I still find myself googling how to do some basic ...

  9. python画二维图_使用python绘制二维图形示例

    我就废话不多说了,直接上代码吧! import matplotlib.pyplot as plt #也可以使用 import pylab as pl import matplotlib.font_ma ...

最新文章

  1. [PyTorch] rnn,lstm,gru中输入输出维度
  2. CF533A Berland Miners
  3. 纵横公路造价软件学习_20年最新公路造价实战培训课程
  4. cannot import name ‘compare_ssim‘
  5. 191. 位1的个数 golang
  6. [导入]ASP.NET 2.0中Page事件的执行顺序
  7. 红米性价比之王宣布!网友:干翻友商小米、干翻友商荣耀
  8. jocky1.0.3 (原joc) java混淆器 去除jdk版本限制
  9. ios 高德地图加载瓦片地图_OpenLayers加载高德地图离线瓦片地图
  10. networkx怎么显示图_如何将标签添加到networkx图形中的节点?
  11. 欧盟ETSI关于汽车雷达的规定
  12. 基于yolov5与Deep Sort的流量统计与轨迹跟踪
  13. 那些我们卖掉的二手iPhone到底去哪了?
  14. mhl数据线_利用MHL数据线 手机同屏到乐视电视X50air上
  15. 2020上海大学生网络安全赛MISC可乐加冰
  16. EmpireToken创造超级代币
  17. 软件体系结构与设计模式——课程总体介绍(01-03)
  18. 风影ASP.NET基础教学 9 数据访问
  19. 效率倍增!12 个必知必会的 Python 数据处理技巧!
  20. 中庸----做人的智慧

热门文章

  1. ARM 架构(V7,V8),和ARM内核区别,从ARM7,ARM9到Cortex-A7,A8,A9,A12,A15到Cortex-A53,A57
  2. matlab 中的dir函数使用
  3. ant vue 树形菜单横向显示_Vue--组件Ant- 树形结构菜单
  4. 006_JSONObject对象公共方法
  5. 048_CSS3用户界面
  6. unity 继承了 获取_获取继承链
  7. c语言程序构造数据类型问题,C语言程序设计课程课件之第四章简单构造数据类型.ppt...
  8. python安装包_在python官网打不开的情况下获取获取官方最新安装包
  9. java中间缓存变量机制_Java中间缓存变量机制
  10. 全面解析Java中的String数据类型