1.后端的几种解决方法
1.在Controller上面加上@CrossOrigin
2.写一个配置文件并且在Controller层加上注解@CORSConfig
package com.wolwo.langyage.base.util;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* CORS configuration
*/
@Configuration
public class CORSConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://127.0.0.1:8080,http://localhost:8080")
.allowedMethods("POST,GET, OPTIONS,DELETE,PUT")
.allowedHeaders("Content-Type,ContentType,Access-Control-Allow-Headers,Access-Control-Allow-Origin, Authorization, X-Requested-With")
.allowCredentials(true);
}
};
}
}
3.在springmvc配置文件里加入
4.写一个过滤器类并且在web.xml中注册过滤器
获取前端传来的数据
2.前端的处理
查看vue版本npm list vue或是在package.json文件里找”dependencies”直接看到
vue2
查看vue版本npm list vue或是在package.json文件里找”dependencies”直接看到
vue2
原理:给url加上了前缀 /api,我们前端发起请求/dev/unit/queryTree访问https://locall/host:8080/dev/unit/queryTree就当于访问了:https://locall/host:8080/api/dev/unit/queryTree
又因为在 index.js 中的 proxyTable 中拦截了 /api ,并把 /api 及其前面的所有替换成了 target 中的内容,因此实际访问 Url 是https://www.wd.com/dev/unit/queryTree。红色是target,绿色是前端发起的具体请求,对应后端的请求
1.vue.main.js 配置访问的url前缀
2.修改config文件夹下的index.js文件,在proxyTable中加上如下代码: 代理,如果没有这部分,那么跨域的路径就是baseurl+具体请求
'/api':{
target: "https://www.wd.com/dev",
changeOrigin:true,
pathRewrite:{
'^/api':'' //因为本身的请求中没有api,所以去掉,eg:前端请求/api/ser,实际后端:https://www.wd.com/dev/ser
}
}
3.app.vue
<template>
<div>
<el-menu></el-menu>
<el-table></el-table>
<br/>
<el-page></el-page>
</div>
</template>
<script>
import nav from "./components/NavMenu.vue"
import eletable from "./components/Table.vue"
import pageination from "./components/Pagination.vue"
export default {
components:{
ElMenu:nav,
ElTable:eletable,
ElPage:pageination
},
data(){
return{}
},
methods:{
},
mounted() {
this.axios({
method: 'get',
url: '/test/test',
params: this.urlParams
}).then((res) => {
console.log(res)
console.log(res.data)
alert(res.data.msg)
}).catch((err) => {
console.log(err)
})
}
}
</script>
3.vue+webpack项目搭建实现前后端交互
1.检查本地环境
node -v
npm -v
vue -V
2.进入目录文件夹创建项目
vue init webpack vue-project-name
3.安装依赖
npm操作: 与cnpm yarn的区别是他们下载源不同,npm会更满=慢些
安装vue-router:
npm install vue-router --save-dev dev表示生产环境,开发环境不加dev
安装element-ui: 与路由相关的元素上需要加上router,在vue文件中的element元素上,如果表单中某个元素的值是变量,需加上: ,比如:key="i"
npm i element-ui -S -S表示plus的意思,不加plus的只支持vue2.几版本,vue3使用plus的
安装SAss加载器:
npm install sass-loader node-sass --save-dev
安装axios:
npm install --save axios vue-axios
注意安装依赖之后要重新执行nmp install
4.启动浏览器进行访问