axios请求SpringBoot数据接口
axios访问SpringBoot的接口需要跨域,故需要在SpringBoot添加CORS配置。
package com.example.util;
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;
/**配置全局跨域
* @author SMILE
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
System.out.println("跨域配置。。。");
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
System.out.println("启动跨域方法。。。。。");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}
请求接口
@RestController
public class AxiosController {
// @ResponseBody用在方法上
// 方法的返回值不再表示view视图页面,而是把返回值直接作为响应结果显示在浏览器上
// @RequestBody用在方法参数上
// 把请求参数编码方式为application/json的对象,转换成一个bean对象
@PostMapping("/axios")
public Role postAxios(@RequestBody Role role){
System.out.println(role);
return role;
}
@GetMapping("/axios")
public Role getAxios(Role role){
System.out.println(role);
return role;
}
}
发送post请求
axios({
method: 'post',
url: 'http://localhost:8083/axios',
data: {
rId:4,
rName:'小红'
}
}).then(res=>{
console.log(res.data);
}).catch(err=>{
console.log(err);
})
发送get请求
axios({
method: 'get',//不写此参数默认为get
url: 'http://localhost:8083/axios',
params: {
rId:4,
rName:'小红'
}
}).then(res=>{
console.log(res.data);
}).catch(err=>{
console.log(err);
})