使用vue-resource发送跨域请求
1、安装vue-resource并引入
1. cnpm install vue-resource -S 2. 参考:GitHub上搜索 vue-resource ,查看API文档:https://github.com/pagekit/vue-resource
2、基本用法
使用this.$http发送请求 this.$http.get(url, [options]) this.$http.head(url, [options]) this.$http.delete(url, [options]) this.$http.jsonp(url, [options]) this.$http.post(url, [body], [options]) this.$http.put(url, [body], [options]) this.$http.patch(url, [body], [options])
3、使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>发送AJAX请求</title> </head> <body> <div id="itany"> <button @click="sendJSONP">向360搜索发送JSONP请求</button> </div> <script src="js/vue.js"></script> <script src="js/vue-resource.min.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ user:{ name:'alice', age:19 }, uid:'' }, methods:{ sendJSONP(){ //https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=a this.$http.jsonp('https://sug.so.360.cn/suggest',{ params:{ word:'python' // 要查询的内容 } }).then(resp => { console.log(resp.data.s); // 返回的查询结果 // ["python官网", "python视频教程", "python 培训", "python基础教程", "python下载", ] }); }, } }); } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>发送AJAX请求</title> </head> <body> <div id="itany"> <button @click="sendJSONP2">向百度搜索发送JSONP请求</button> </div> <script src="js/vue.js"></script> <script src="js/vue-resource.min.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ user:{ name:'alice', age:19 }, uid:'' }, methods:{ sendJSONP2(){ //https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&json=1&p=3&sid=1420_21118_17001_21931_23632_22072&req=2&csor=1&cb=jQuery110208075694879886905_1498805938134&_=1498805938138 this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{ params:{ wd:'a' }, jsonp:'cb' //百度使用的jsonp参数名为cb,所以需要修改 }).then(resp => { console.log(resp.data.s); // ["爱奇艺", "阿黛尔", "艾力绅", "阿里云", "阿里巴巴", "安居客", ] }); } } }); } </script> </body> </html>
4、发送get请求,并将请求内容添加到插件中
get(url, option)
Url :表示请求地址
Option :表示请求配置
Params :定义query数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <div id="app"> <h1>vue实例化对象</h1> <router-view></router-view> <!--定义渲染容器--> </div> <script type="text/javascript" src="vue.js"></script> <script type="text/javascript" src="vue-router.js"></script> <script type="text/javascript" src="vue-resource.min.js"></script> <script> var Home = { template:'<h1>home--{{data}}</h1>', data:function () { return { data:'' } }, created:function () { this.$http.get('demo.json?123',{ params:{ color:'red' } }) .then(function (res) { this.data = res.data.name // res.data 是请求获取的内容 }) } }; // 第一步:定义路由规则 var routes = [ { path:'/home', name:'home', component:Home }, ]; // 第二步:实例化路由对象 var router = new VueRouter({ routes:routes }); // 第三步:在vue实例化对象中注册路由 var app = new Vue({ el:'#app', router:router }) </script> </body> </html>
5、发送post请求
post(url, data, option)
Url :表示请求地址
Data :表示请求的数据
Option :表示请求的配置
Params :定义query数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <div id="app"> <h1>vue实例化对象</h1> <router-view></router-view> <!--定义渲染容器--> </div> <script type="text/javascript" src="vue.js"></script> <script type="text/javascript" src="vue-router.js"></script> <script type="text/javascript" src="vue-resource.min.js"></script> <script> var Home = { template:'<h1>home--{{data}}</h1>', data:function () { return { data:'' } }, created:function () { this.$http.post('demo.json?123',{'arg1':'price'},{ params:{ b:200 } }) .then(function (res) { this.data = res.data.name // res.data 是请求获取的内容 }) } }; // 第一步:定义路由规则 var routes = [ { path:'/home', name:'home', component:Home }, ]; // 第二步:实例化路由对象 var router = new VueRouter({ routes:routes }); // 第三步:在vue实例化对象中注册路由 var app = new Vue({ el:'#app', router:router }) </script> </body> </html>
1.4 封装axios请求
1、初始化环境
vue init webpack deaxios
npm install axios –S
cnpm install vuex -S
2、封装axios(创建 src/api 文件夹)
config\urls.js 配置全局url变量
export default { // api请求地址 // API_URL: 'http://mup.dev.yiducloud.cn/' API_URL: 'http://1.1.1.3:8888' }
import Axios from 'axios' import URLS from '../../config/urls' //1、使用自定义配置新建一个 axios 实例 const instance = Axios.create({ baseURL: URLS.API_URL, headers: { 'Content-Type': 'application/json' } }); //2、添加请求拦截器 instance.interceptors.request.use( config => { //发送请求前添加认证token config.headers.Authorization = sessionStorage.getItem('token') // console.log(sessionStorage.getItem('token'),11223344) return config }, err => { return Promise.reject(err) }); //3、添加响应拦截器 instance.interceptors.response.use(function (response) { // 对响应数据处理 if (response.status === 200 || response.status === 201 || response.status === 400) { const data = response.data if (data.code === 200 || data.code === 201) { return data } } return Promise.reject(response) }, function (error) { if (error.response) { switch (error.response.status) { case 400: return Promise.reject(error.response.data) case 401: window.location.href = '/login' } } // const errorData = error.response.data // if (errorData.code === 400) { // return Promise.reject(errorData.desc) // } // return Promise.reject(errorData) }) // export const getNodegroups = params => { return instance.get(`${base}/nodegroup/v1/nodegroups/list/`, params).then(res => res.data) } // export const getNodegroups = params => { return instance.get(`/nodegroup/v1/nodegroups/list/`, params).then(res => res) } export default instance
import URLS from '../../config/urls' import ajax from './ajax' let base = URLS.API_URL // 用户相关 export const requestLogin = params => { return ajax.post(`${base}/users/v1/user/login/`, params).then(res => res) }
import * as api from './api' export default api
3、使用vuex
import Vue from 'vue' import Vuex from 'vuex' import login from './modules/login/login' Vue.use(Vuex); export default new Vuex.Store({ modules:{ login } });
import { requestLogin, } from '../../../api/api' // 导入封装后的axios请求 const state = {} const getters = {} const actions = { async loginMethod ({commit}, params) { return requestLogin(params).then(response => response) }, }; const mutations = {} export default { state, getters, actions, mutations }
4、入口
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import store from './store/index' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
<template> <div id="app"> <p @click="handleLogin">点击发送axiso请求</p> <router-view/> </div> </template> <script> import { mapActions } from 'vuex' export default { name: 'App', methods: { ...mapActions(['loginMethod']), handleLogin () { var loginParams = { username: 'zhangsan', password: '123456' } this.loginMethod(loginParams).then(response => { // this.logining = false sessionStorage.setItem('token', response.data) // this.$router.push({ path: '/' }) }).catch(error => { this.loading = false this.error(error.desc ? error.desc : '服务器异常') }) } }, } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
5、封装axios作用
1. 我们在此将此项目所用到的所有接口调用方法都做了定义,这样既方便查看也利于管理。在
2. 我们需要调用接口方法的时候,我们只需要在对应vue文件中的标签里直接import想用的接口方法就行了
例如:import { getOptList,branchList,addOperator } from "../../api/index";
6、使用vuex发送get请求
import Vue from 'vue' import Vuex from 'vuex' import meeting from './modules/meeting/meeting' Vue.use(Vuex) export default new Vuex.Store({ strict: process.env.NODE_ENV !== 'production', modules: { meeting } })
import { getMeetingList } from '../../../api/api' import {getUrl} from "../../../utils/global/geturl"; // 导入封装后的axios请求 const state = {}; const getters = {}; const actions = { async getMeetingListMethod ({commit}, params) { return getMeetingList(getUrl(params)).then(response => response) }, }; const mutations = {}; export default { state, getters, actions, mutations }
<template> </template> <script> import { mapActions } from 'vuex' export default { data() { return {}; }, methods: { ...mapActions(['getMeetingListMethod']), // 获取会议室信息 requestMeetingListMethod () { var parms = {}; this.getMeetingListMethod(parms).then(response => { console.log(123456) console.log(response) // this.tableData = response.data.data_list // this.listQuery.total = response.data.total this.loading = false }).catch(error => { this.loading = false; this.error(error.desc ? error.desc : '服务器异常') }) }, }, created(){ this.requestMeetingListMethod(); // 获取会议室信息 }, }; </script> <style scoped> </style>