1.安装axois
2.main.js引入并配置
import axios from 'axios'
Vue.prototype.$ajax= axios
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.baseURL = "http://xxxx.natapp1.cc/xm"
3.POST提交参数,POST提交参数的格式有严格要求,如果前后台搭配不当,就会出现问题。根据参数传递的数量,有两种POST的提交方式。
(1)POST参数少的时候
postTest(){
//参数少
var param = new URLSearchParams();
param.append('emailAccount','xxx996537@qq.com');
this.$ajax({
method: 'post',
url: '/v_register',
data:param
})
.then(function(response){
console.log(response.data)
alert("post success!");
})
.catch(function(error){
console.log(error);
})
}
此时对应的后端接收参数格式为:
@PostMapping("/v_register")
public Result v_register(String emailAccount){}
(2)POST参数多的时候
//参数多 ,构造json:
data{'id':'1','name':'小明'…}
this.$ajax({method: 'post',
url: '/v_register',
data:data
})
.then(function(response){
console.log(response.data)
alert("post success!");
})
.catch(function(error){
console.log(error);
})
},
此时对应的后端接收参数格式为:
@PostMapping("/v_registers")
public Result v_register(Object user){}
4.后端SpringBoot配置跨域
(1)将SpringBoot的版本调到2.0或者以下
(2)配置Config
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;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @Auther: Chandler
* @Date: 2018/6/11 15:43
* @Description: 配置跨域
*/
@Configuration
public class CorsConfig{
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1
corsConfiguration.addAllowedHeader("*"); // 2
corsConfiguration.addAllowedMethod("*"); // 3
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}