Vuejs中设置代理进行跨域的方法

mac2025-08-13  5

在vue工程中根目录增加一个配置文件:vue.config.js

module.exports = { // 修改的配置 devServer: { host:"0.0.0.0", disableHostCheck: true, // https: true, proxy: { "/api/": { "target": "http://localhost:8090/", changeOrigin: true, ws: true, pathRewrite: { '^/api': '/' } },"/rest/": { "target": "http://localhost:8000/", changeOrigin: true, ws: true, pathRewrite: { '^/rest': '/' } } } } }

安装axios

cnpm install axios --save-dev

在main.js中引入axios

import Vue from 'vue' import App from './App.vue' import router from './router' import axios from 'axios' Vue.use(axios); Vue.config.productionTip = false Vue.prototype.$axios = axios; new Vue({ router, render: h => h(App) }).$mount('#app')

在业务代码中增加一个方法和一个按钮

methods: { getData() { window.console.info(1111111); // 1:可以访问后端接口已经做了跨域设置的接口this.$axios.get("http://localhost:8090/hello").then((data)=>window.console.info(data)) //2:可以直接调用使用Vue做了代理的接口 // this.$axios.get("/api/hello").then((data)=>window.console.info(data)) // this.$axios.get("/rest/user/").then((data)=>window.console.info(data)) this.$axios .get("http://localhost:8090/hello") .then(data => window.console.info(data)); } }

按钮触发事件

<button @click="getData()">请求接口</button>

获取如下内容并打印出来。 如果不想使用代理,则可以在后端接口做跨域支持: springboot中在主类加入如下两个方法:

private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用 corsConfiguration.addAllowedHeader("*"); // 2允许任何头 corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等) return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); // 4 return new CorsFilter(source); }

后端跨域之后,前端也不用再设置代理访问了。

最新回复(0)