Vue中axios跨域交互

下载插件支持

npm install element-ui -S
安装elementUI支持
npm install axios -S
安装axios插件支持
npm install qs -S
安装qs,在使用get提交和post提交时使用
npm install vue-axios -S
在整合时使用

axios跨域传值验证登陆

1.开启需要传值的两个服务
后台服务,主要接收前台传来的值来验证用户名和密码是否正确

在这里插入图片描述

在这里插入图片描述

前台部分
src目录下找到main.js,并在指定位置添加三行代码
main.js是入口文件,所以在这里引入就行,页面就不用引入了

import ElementUI from ‘element-ui’ //新添加1

import ‘element-ui/lib/theme-chalk/index.css’ //新添加2,避免后期打包样式不同,要放在import App from ‘./App’;之前

Vue.use(ElementUI) //新添加3

位置如
// 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 ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App'
import router from './router'


Vue.use(ElementUI) //新添加3
Vue.config.productionTip = false




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

HTML原型界面,可以从elementUI官网复制
<el-form :model="ruleForm" label-width="100px" class="demo-ruleForm login-container">
			<h2 style="text-align: center;">用户登录</h2>
			<el-form-item label="用户名" prop="uname">
				<el-input type="text" placeholder="用户账号" v-model="ruleForm.uname" autocomplete="off"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="pwd">
				<el-input type="password" placeholder="用户密码" v-model="ruleForm.pwd" autocomplete="off"></el-input>
			</el-form-item>
			<el-form-item>
				<el-row>
					<el-col :span="24">
						<div class="grid-content bg-purple-dark">
							<el-button type="primary" style="width: 80%;" plain @click="doSub()">登录</el-button>
						</div>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<div class="grid-content bg-purple-dark">
							<el-link type="primary" @click="addUser">用户注册</el-link>
						</div>
					</el-col>

					<el-col :span="12">
						<div class="grid-content bg-purple-dark">
							<el-link type="primary">忘记密码</el-link>
						</div>
					</el-col>
				</el-row>

			</el-form-item>
		</el-form>

在data定义属性,用于后面用户名和密码文本框里值的获取

data() {
			return {
				ruleForm: {
					uname: '',
					pwd: ''

				}
			};
		}

get提交

<script>
	/* 引用axios */
	 import axios from 'axios'  
	/* 引用qs支持post提交 */
	 import qs from 'qs' 

	export default {
		data() {
			return {
				ruleForm: {
					uname: '',
					pwd: ''

				}
			};
		},
		methods: {
		//在点击登陆按钮触发事件
			doSub: function() {
			//获取用户名和密码并保存到params对象中
				let params = {
					username: this.ruleForm.uname,
					password: this.ruleForm.pwd,
					methodName: 'userLogin'
				};
				/* console.log(params); */

//'http://localhost:8080/j2eeVue/userAction.action',后台的提交路径
			axios.get('http://localhost:8080/j2eeVue/userAction.action', { //注意数据是保存到json对象的params属性
					params: params
				}).then(function(response) {
					console.log(response);
				}).catch(function(error) {
					console.log(error);
				});
			},

			addUser() {
				this.$router.push({
					path: '/AddUser'
				});
			}
		}

	}
</script>
post提交只需要将上面的get提交部分改掉
//将params中json对象转换成url数据
    let str = qs.stringify(params);
				axios.post('http://localhost:8080/j2eeVue/userAction.action', str).then(function(response) {
					console.log(response.data);
				}).catch(function(error) {
					consolae.log(error);
				}); 
将登陆页面部署到路由
import Vue from 'vue'
import Router from 'vue-router'
/* import HelloWorld from '@/components/HelloWorld' */
import Long from '@/views/Long'

Vue.use(Router)

export default new Router({
  routes: [
     	{
			path: '/',
			name: 'Long',
			component: Long
		},
		{
			path: '/Long',
			name: 'Long',
			component: Long
		},
		
		
  ]
})

将重复的使用的部分放入全局

对请求的地址封装
/**
 * 对后台请求的地址的封装,URL格式如下:
 * 模块名_实体名_操作
 */
export default {
	'SERVER': 'http://localhost:8080/j2eeVue', //服务器
	'SYSTEM_USER_DOLOGIN': '/userAction.action', //登陆
	'SYSTEM_USER_DOREG': '/userAction.action', //注册
	'SYSTEM_MODULE_TREEBODE':'/moduleAction.action',
	'getFullPath': k => { //获得请求的完整地址,用于mockjs测试时使用
		return this.SERVER + this[k];
	}
}

Vue项目对axios的全局配置
/**
 * vue项目对axios的全局配置
 */
import axios from 'axios'
import qs from 'qs'

//引入action模块,并添加至axios的类属性urls上
import action from '@/api/action'
axios.urls = action

// axios默认配置
axios.defaults.timeout = 10000; // 超时时间
// axios.defaults.baseURL = 'http://localhost:8080/j2ee15'; // 默认地址
axios.defaults.baseURL = action.SERVER;

//整理数据
// 只适用于 POST,PUT,PATCH,transformRequest` 允许在向服务器发送前,修改请求数据
axios.defaults.transformRequest = function(data) {
	data = qs.stringify(data);
	return data;
};


// 请求拦截器
axios.interceptors.request.use(function(config) {
	return config;
}, function(error) {
	return Promise.reject(error);
});

// 响应拦截器
axios.interceptors.response.use(function(response) {
	return response;
}, function(error) {
	return Promise.reject(error);
});

// // 路由请求拦截
// // http request 拦截器
// axios.interceptors.request.use(
// 	config => {
// 		//config.data = JSON.stringify(config.data);  
// 		//config.headers['Content-Type'] = 'application/json;charset=UTF-8';
// 		//config.headers['Token'] = 'abcxyz';
// 		//判断是否存在ticket,如果存在的话,则每个http header都加上ticket
// 		// if (cookie.get("token")) {
// 		// 	//用户每次操作,都将cookie设置成2小时
// 		// 	cookie.set("token", cookie.get("token"), 1 / 12)
// 		// 	cookie.set("name", cookie.get("name"), 1 / 12)
// 		// 	config.headers.token = cookie.get("token");
// 		// 	config.headers.name = cookie.get("name");
// 		// }
// 		return config;
// 	},
// 	error => {
// 		return Promise.reject(error.response);
// 	});

// // 路由响应拦截
// // http response 拦截器
// axios.interceptors.response.use(
// 	response => {
// 		if (response.data.resultCode == "404") {
// 			console.log("response.data.resultCode是404")
// 			// 返回 错误代码-1 清除ticket信息并跳转到登录页面
// 			//      cookie.del("ticket")
// 			//      window.location.href='http://login.com'
// 			return
// 		} else {
// 			return response;
// 		}
// 	},
// 	error => {
// 		return Promise.reject(error.response) // 返回接口返回的错误信息
// 	});



export default axios;

在main.js入口文件,将axios配置到全局
// 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 ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App'
import router from './router'
//这是上面Vue项目对axios的全局配置文件的路径
 import axios from '@/api/http'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
 
Vue.use(ElementUI) //新添加3
Vue.config.productionTip = false




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

配置完后的get和post提交

get提交
//SYSTEM_USER_DOLOGIN是上面对请求路径封装文件中的路径名
this.axios.get(this.axios.urls.SYSTEM_USER_DOLOGIN, {
					params: params
				}).then(resp => {
					console.log(resp.data);
				}).catch(resp => {});
post
this.axios.post(this.axios.urls.SYSTEM_USER_DOLOGIN, params).then(resp => {
					console.log(resp.data);
				}).catch(resp => {});

效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值