前后分离项目中,有一个需要解决的问题就是跨域问题,我使用idea创建springboot2.X项目,使用webstorm创建的vue cli4.0,默认新建的vue cli4中并没有vue.config,js配置文件,可以在根目录下(非src文件夹下)新建该配置文件,在里面写跨域的配置。springboot后端不做任何配置,只在前端vue中配置
首先,默认创建vue cli3及以上项目时,是没有vue.config.js文件的,需要自己先新建一个文件,放到根目录下,非src下
如下图所示:
应该放到如上图所示的地方,然后在里面填写基本的配置信息
如下图所示:
module.exports = {
// 将部署应用程序的基本URL
// 将部署应用程序的基本URL。
// 默认情况下,Vue CLI假设您的应用程序将部署在域的根目录下。
// https://www.my-app.com/。如果应用程序部署在子路径上,则需要使用此选项指定子路径。例如,如果您的应用程序部署在https://www.foobar.com/my-app/,集baseUrl到'/my-app/'.
publicPath: process.env.NODE_ENV === 'production' ? './' : './',
// outputDir: 在npm run build时 生成文件的目录 type:string, default:'dist'
outputDir: 'dist',
// pages:{ type:Object,Default:undfind }
/*
构建多页面模式的应用程序.每个“页面”都应该有一个相应的JavaScript条目文件。该值应该是一
个对象,其中键是条目的名称,而该值要么是指定其条目、模板和文件名的对象,要么是指定其条目
的字符串,
注意:请保证pages里配置的路径和文件名 在你的文档目录都存在 否则启动服务会报错的
*/
pages: {
index: {
//entry for the page
entry: 'src/main.js',
//the source template
template: 'public/index.html',
//output as dist/index.html
filename: 'index.html'
},
// when using the entry-only string format,
// template is inferred to be `public/subpage.html`
// and falls back to `public/index.html` if not found.
// Output filename is inferred to be `subpage.html`.
// subpage: 'src/subpage/main.js'
},
// lintOnSave:{ type:Boolean default:true } 问你是否使用eslint
lintOnSave: true,
// productionSourceMap:{ type:Bollean,default:true } 生产源映射
// 如果您不需要生产时的源映射,那么将此设置为false可以加速生产构建
productionSourceMap: false,
// devServer:{type:Object} 3个属性host,port,https
// 它支持webPack-dev-server的所有选项
devServer: {
port: 8080, // 端口号
host: 'localhost',
https: false, // https:{type:Boolean}
open: true, //配置自动启动浏览器
proxy: {// 配置跨域处理,只有一个代理
"/api": {
target: "http://localhost:8082/api", // 要访问的接口域名
ws: true, // 是否启用websockets
changeOrigin: true, //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
pathRewrite: {
'^/api': "/" //这里理解成用'/api'代替target里面的地址,比如我要调用'http://40.00.100.100:3002/user/add',直接写'/api/user/add'即可
}
}
}
/*css: {
loaderOptions: {
css: {},
postcss: {
plugins: [
/!*require('postcss-px2rem')({
remUnit: 37.5
})*!/
]
}
}
}*/
}
};
跨域请求主要就是在proxy对应的大括号里面进行配置,下面说下在springboot端的controller层上的写法
如下图所示:
@RestController
@RequestMapping("api/book")
//@Slf4j
public class BookController {
@Resource
BookMapper bookMapper;
@GetMapping("/findAll")
public List<Book> findAll(){
System.out.println("findall方法被调用-------------------------------------------------");
return bookMapper.selectList(null);
}
}
方法是在mybatis plus框架下访问数据库得到结果,其中Book类代码如下:
package com.smp.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
@Data
@TableName("book")
public class Book implements Serializable {
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
@TableField("name")
private String name;
@TableField("author")
private String author;
}
如果对mybatis plus不是很熟悉的,可以将查询mapper及其数据库操作的语句注释掉,直接编写硬编码返回即可,
在vue中返回的语句如下,在Book.vue中
<script>
export default {
name: 'Book',
data(){
return{
books:[]
}
},
created(){
this.$myAxios.get('/api/book/findAll')
.then(res=>{
console.log('res.data:',res.data);
})
.catch(err => {
console.log(err.data.message);
});
}
}
</script>
myAxios是对axios的简单封装,这里可以使用原生axios代替,通过get后面的url访问springboot的controller层findAll方法,最后在谷歌浏览器控制台打印效果如下: