日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python 之CORS,VUE+rest_framework示例

發(fā)布時間:2025/4/16 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 之CORS,VUE+rest_framework示例 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一、跨域

? ? 瀏覽器的同源策略

? ? ? ? ? ? ? ? ----對ajax請求進行阻攔

? ? ? ? ? ? ? ? ----對href屬性讀不阻攔

? ? ? ?xhr=new XMLHttpRequest

? ? ? ?xhr.open...

? ? ? ?xhr.send(...)

? ?解決方案:

? ? ? ?---JSONP

? ? ? ? ? ? ? ? ?點擊按鈕:?

? ? ? ? ? ? ? ? ? ? ? ? 動態(tài)添加一個

<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網(wǎng)站:
<input type="button" value="獲取用戶數(shù)據(jù)" ο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>

服務(wù)商:
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. 復(fù)雜請求(性能上的損耗,options預(yù)檢,真實的請求)
A網(wǎng)站:
<input type="button" value="獲取用戶數(shù)據(jù)" ο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>

服務(wù)商:

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

創(chuàng)建腳手架:
vue init webpack Vue項目名稱
# Install vue-router? Yes


插件:
axios,發(fā)送Ajax請求
vuex,保存所有組件共用的變量
vue-cookies,操作cookie


流程:
1. 創(chuàng)建腳手架

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: ''
}
},
# 加載時執(zhí)行
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 調(diào)用
state: {
username: Cookie.get('username'),
token: Cookie.get('token')
},
mutations: {
// 組件中通過 this.$store.commit(參數(shù)) 調(diào)用
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 調(diào)用
state: {
username: Cookie.get('username'), # vue-cookies
token: Cookie.get('token') # vue-cookies
},
mutations: {
// 組件中通過 this.$store.commit(參數(shù)) 調(diào)用
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參數(shù)
<router-link :to="{'path':'/course-detail/'+item.id }">{{item.name}}</router-link>
<router-link to="/index">首頁</router-link>

# 獲取傳過來的參數(shù)
this.$route.params.id
# 重定向
this.$router.push('/index')

?

轉(zhuǎn)載于:https://www.cnblogs.com/mengqingjian/p/8436358.html

總結(jié)

以上是生活随笔為你收集整理的python 之CORS,VUE+rest_framework示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。