本文详细介绍了如何在Vue项目中使用axios进行HTTP请求,并配置了CORS以处理前后端通信。包括设置基础URL,创建页面调用函数,以及在WebConfig中添加CORS映射。
摘要由CSDN通过智能技术生成
1、第一步先确定基础的URL 2、在main.js中设置基础的
3、先在Vue中定义axios:
npm i axios -S
3.1 在main.js导入源码
import axios from "axios"; Vue.prototype.$http=axios; axios.defaults.baseURL="http://localhost:9000"
4、拼接基础的URL
5、创建页面调用函数
6、后端配置util中进行配置类:创建WebConfig.java
@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:8080") .allowedMethods("GET","POST","PUT","OPTIONS","DELETE") .allowCredentials(true) .maxAge(3600); } }
7、前端的路径,工具类的路径要一样
8、Vue中定义的方法
methods: { getVideoList(){ axios.get("/videolist") .then((res) => { this.videoList = res.data console.log(this.videoList) }) }, getImgURL(imgId){ return "http://localhost:9000/static/img/" + imgId + ".jpg" } }, created() { this.getVideoList(); }