axios网络请求
对比其他网络请求方法
传统的Ajax——基于XMLHttpRequest(XHR)
- 配置和调用方式等非常混乱
- 编码起来非常繁琐
JQuery——Ajax
相对于传统的Ajax编程方式非常友好,但是在Vue开发中,为了使用一个网络请求特意引进了一个JQuery有点大材小用
Vue-resource
相对于JQuery,Vue-resource的体积小很多,但是在Vue2.0后退出,作者也在GitHub的Issues中说明了去掉了Vue-resource
axios功能特点
- 在浏览器中发送XMLHttpRequest请求
- 在node.js中发送http请求
- 支持Promise API
- 拦截请求和响应
- 转换请求和响应数据
axios全局配置
- axios.defaults.baseURL
- axios.defaults.headers.post['content-Type']='application/x-wwww-form-urlencoded'
axios常见的配置选项
- 请求地址
url: '/user'
- 请求地址
method: 'get'
- 请求根路径
baseURL: 'http://xxxx'
- 请求前的数据处理
transformRequest: [function(data){}]
- 请求后的数据处理
transformResponse: [function(data){}]
- 自定义请求头
header: {'x-Requested-with':'XMLHttpRequest'}
- URL查询对象
params: {id: 12}
- request body
data: {key: value}
axios请求方式
- axios(config)
- axios.request(config)
- axios.get(url[, config])
- axios.head(url[, config])
- axios.post(url[,data[,config]])
- axios.put(url[,data[,config]])
- axios.patch(url[,data[,config]])
跨域问题
项目部署在demo1.com服务器上时,是不能直接访问dome2.com服务器上的资料的。
通过后台解决
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}