vue中请求后端的接口获取数据:
created() {
const _this = this;
axios.get('http://localhost:8181/book/findAll').then(function (resp){
_this.books=resp.data;
})
}
如果后端不做处理,那是请求不了的,可以从两个方面进行处理,1:后端解决,2:前端解决
后端解决
在config这个包下创建一个类:CrosConfig.java
/**
* <p>
* 解决跨域
* </p>
*
* @author wangmh
* @since 2022/10/4 14:58
*/
@Configuration
public class CrosConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
这样前端不需要做任何处理,直接正常请求即可
前端处理
后端处理接口会被暴露,所以可以采用前端处理,采用前端处理,后端接口不需要改动
这时候只需要去修改 vue.config.js
这段代码的意思是把所有带有 /api 请求都转发到指定的服务器端口
module.exports = {
lintOnSave: false,
devServer: {
proxy: {
'/api': {
target: "http://localhost:8181",
changOrigin: true, //开启代理
pathRewrite: {
'^/api': ''
}
}
}
}
}
接下来 axios 就这样请求:
created() {
const _this = this;
axios.get('/api/book/findAll').then(function (resp){
_this.books=resp.data;
})
}
或者
methods: {
sendHttp() {
axios({
url: "/api/book/findAll",
method: "POST",
contentType: "application/json",
params: {
pageNum: 1,
username: "红楼梦"
},
})
.then(async (res) => {
this.tableData = res.data.list;
})
.catch((err) => {
return err;
});
}
}