1.安装axios:npm install axios
2.如何调用后端接口?
后台接口写法如下:返回结果是个json串,自己随意发挥
@ResponseBody
@RequestMapping(value = "/selShip", method = RequestMethod.POST, produces = "application/json")
public MyResult selShip(@RequestBody JSONObject jsonParam){
SHIP ship=JSONUtil.toBean(jsonParam,SHIP.class);
List<SHIP> shiplist=apiMapper.selectship(ship);
JSON js=JSONUtil.parse(shiplist);
System.out.println(js);
return ResultUtil.success(js);
}
前台Vue axios写法如下:点击按钮调后端接口
<template>
<div class="test">
<el-button @click="gogo()" >提交</el-button>
</div>
</template>
<style scoped></style>
<script>
import axios from "axios";
export default {
data() {
return {
info:"{}"
};
},
methods: {
gogo(){
console.log("gogo");
axios.get('http://localhost:12177/miku1').then(res=>{console.log(res)})
axios.post('http://localhost:12177/selShip',this.info).then(res=>{console.log(res)})
}
},
mounted() {
axios.defaults.headers.post['Content-Type'] = 'application/json';
}
};
</script>
调用结果如下:上面红圈是get请求,下面的是post请求的返回结果
3.问题汇总与解决方案
遇到的问题1:前端Vue4 使用 axios post请求后台接口出现 been blocked by CORS policy
解决方案:后端新建配置类允许请求跨域即可
package com.gzgdata.xinshagatepromotion.config;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootConfiguration
public class MyWebConfiger implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry corsRegistry){
/**
* 所有请求都允许跨域,使用这种配置就不需要
* 在interceptor中配置header了
*/
corsRegistry.addMapping("/**")
.allowCredentials(true)
.allowedOrigins("http://localhost:50001")//Vue运行时的地址
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.allowedHeaders("*")
.maxAge(3600);
}
}
遇到的问题2:出现415错误
解决方案:axios调用前设置header的Content_Type的值与后端的接口配置一样
axios.defaults.headers.post['Content-Type'] = 'application/json';
4.axios 封装与拦截器