前后端分离,axios接口联调,跨域快速上手
使用axios,前端向后端发送数据
使用axios向后端发送请求由多种方式,和ajax的功能相同,只是实现方式不同
1,使用axios起步
首先在idea上面创建两个工程,一个web工程,一个springboot工程
在这个测试中,我们使用的axios是cdn,需要联网使用
1,配置springbot工程
创建一个实体类
创建一个控制器类,用来接收前端发来的数据并且处理返回json数据类型
package com.zzulil.vue.springbootserver.controller;
import com.zzulil.vue.springbootserver.entity.Person;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//这个注解的意思是方法种所有的返回对象都是json对象
@RestController
public class MyController {
@RequestMapping("/user/person")
//这个注解的意思是解决跨域的问题
@CrossOrigin
public Person test01(){
return new Person("小明","111");
}
}
配置一个端口号
2,创建一个web工程使用axios来发送请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<h1>hell world !!!</h1>
<script type="text/javascript">
axios.get('http://localhost:8088/user/person')
//then 获取后台的数据
.then(function (response) {
//打印到控制台中
console.log(response);
})
.catch(function (error) {
console.log(error);
});
</script>
</body>
</htm
在后端服务开启的前提下打开页面
2,axios API(传参到后台)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
axios({
url:'http://localhost:8088/user/person',
method:'post',
//设置一个参数传送到后台
params:{password:'我是前端穿过来的密码'}
}).then(res => {
//获取从后台拿到的数据,指定为data(这是固定的)
console.log(res.data);
}).catch(error=>{ //捕获所有的错误信息,并且在控制台输出
console.log(error);
})
</script>
</body>
</html>
修改以下处理方法,将参数传递过去
开启服务,打开html页面查看页面输出控制台
3,简化axios的请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
<!--只能使用post方式 axios.port(url , 参数)-->
axios.post('http://localhost:8088/user/person',{password:'我是json对象'})
.then(res=>{
console.log(res);
}
)
</script>
</body>
</html>
开启服务后端接收参数
package com.zzulil.vue.springbootserver.controller;
import com.zzulil.vue.springbootserver.entity.Person;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//这个注解的意思是方法种所有的返回对象都是json对象
@RestController
public class MyController {
@RequestMapping("/user/person")
//这个注解的意思是解决跨域的问题
@CrossOrigin
public Person test01(@RequestBody String password){ //@RequestBody的意思是从前端传过来的json对象
System.out.println(password);
return new Person("小明",password);
}
}
查看页面
4,axios的全局配置(就是将每个axios的共同部分统一管理)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
<!--只能使用post方式 axios.port(url , 参数)-->
/*
* 配置默认值
* 你可以指定将被用在各个请求的配置默认值
* axios.defaults.baseURL = 'http://api.example.com';
* axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
* axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
* */
//设置全局配置信息
axios.defaults.baseURL = 'http://localhost:8088/';
//设置请求超时时间
axios.timeout=5;
axios.post('user/person',{password:'我是json对象'})
.then(res=>{
console.log(res);
}).catch(error=>{ //捕捉错误信息
console.log(error)
})
</script>
</body>
</html>
打开浏览器页面
== 自定义全局配置==
// 创建实例时设置配置默认值
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// 实例创建之后可修改默认配置
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
5,axios拦截器介绍
搭配axios这个工具来做http请求,有时我们需要配置一些全局参数,比如token了,设置超时时间了,未登录状态剔除了等等,这个参数是非常多的,我们不能一个一个添加请求,最好的办法就是使用拦截器让么个请求都可以加上配置参数**
1,拦截器分为request请求拦截器和response响应拦截器
**request请求拦截器:发送前 请求统一处理,比如设置请求头,应用的版本号,终端类型等,
response响应拦截器:有时候我们根据响应的状态码来进行下一步操作,例如当前的token过期,接口返回401未授权,那我们需要进行重新登录的操作。**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
<!--只能使用post方式 axios.port(url , 参数)-->
//设置全局配置信息
axios.defaults.baseURL = 'http://localhost:8088/';
//设置请求超时时间
//axios.timeout=5;
//设置请求拦截器
axios.interceptors.request.use(
config => {
//设置一个token
let token = '我是token1111';
//打印token
console.log(token);
debugger
//返回
return config;
}, error => {
debugger
//对请求的错误信息做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器
axios.interceptors.response.use(
function (response) {
// 对响应数据做点什么
console.log('我进入响应拦截器了');
return response;
},
function (error) {
// 对响应错误做点什么
return Promise.reject(error);
}
);
//使用axios进行发送请求
axios.post('user/person', {password: '我是json对象'})
.then(res => {
console.log(res);
}).catch(error => { //捕捉错误信息
console.log(error)
})
</script>
</body>
</html>
开启服务打开页面
5,跨域背景
1,什么是跨域
url的一般格式:协议+域名(子域名+主域名)+端口号+资源地址实例
http://www…dustyblong.cn:8080/say/hello
只要协议,子域名,主域名,端口号者四项组成部分有一项不同,就可以认为是不同的域,不同域之间跨越相互访问资源,我们称之为跨域。
在后端增加一个控制方法,没有开启跨域
使用前端的页面使用axios进行访问
打开浏览器
2,统一处理跨域配置
在java后端创建一个配置类用来配置跨域的请求,以下是一些简单的配置,可以根据自己的需求增加
package com.zzulil.vue.springbootserver.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//表明这个类是一个配置类
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("*") //允许任何请求头
.allowedMethods("*") //允许任何方法
.allowedOrigins("*") //允许跨域的域名
.maxAge(360L);
}
};
}
}
在后端控制类中清除所有的跨域配置
重新访问没有设置跨域的页面
6,使用 form表单传递参数
1,失去焦点验证
Form 组件提供了表单验证的功能,只需要通过 rules 属性传入约定的验证规则,并将 Form-Item 的 prop 属性设置为需校验的字段名即可,rules属性是在 data{} 中 rules是一个对象
:model 代表双向绑定
:rules=“rules” 代表启用规则 ,rules在data数据属性中
ref 起别名
prop 给组件传参 然后交给rules对象相同的name属性进行操作,进行校验
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" ........>
<el-form-item label="活动名称" prop="name">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
</el-form
<script>
export default {
name: 'test',
data() {
return {
ruleForm: {
name: '',
region: '',
date1: '',
date2: '',
delivery: false,
type: [],
resource: '',
desc: ''
},
rules: {
name: [
//trigger 代表 失去焦点
{ required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
]
methods: {
onsubmit(){
cosole.log('submit');
}
}
</script>
2,form表单进行提交验证
如果表单提交验证成功,我们就在验证成功的方法中使用 axios或者其封装类向后台传送数据
使用validate方法,对整个表单进行校验的方法,参数为一个回调函数。该回调函数会在校验结束后被调用,并传入两个参数:是否校验成功和未通过校验的字段。若不传入回调函数,则会返回一个 promise
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" ........>
<el-form-item label="活动名称" prop="name">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
</el-form
........
//其中submitForm方法的参数是 ref对组件起的别名 是一个组件对象
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">点击提交</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
..........
//创建一个点击事件,当点击发生时,触发submitForm
<script>
methods: {
//formName只是一个参数名,传过来什么就是什么
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
//走到这里说明已经是表单验证成功了,我们在这个位置编写axiox
//向后端发送数据。
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
</script
知识点补充
**在JavaScript中需要通过document.querySelector("#demo")来获取dom节点,然后再获取这个节点的值。在Vue中,我们不用获取dom节点,元素绑定ref之后,直接通过this.$refs即可调用,这样可以减少获取dom节点的消耗。
ref介绍
ref被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向该子组件实例
通俗的讲,ref特性就是为元素或子组件赋予一个ID引用,通过this.$refs.refName来访问元素或子组件的实例
//使用ref表明dom的名字 children
<p ref="p">Hello</p>
<children ref="children"></children>
//通过ref的名字调用,this.$refs 是所有ref的集合,通过ref名称来具体调用
this.$refs.p
this.$refs.children