实现在服务器上跨域
在游览器上禁止跨域,但是在服务器上可以
前后端分离项目前端需要进行跨域访问到后端接口
在Vue工程的根目录下创建 vue.config.js 文件
let proxyObj = {} //定义代理对象
proxyObj['/'] = {
//websocket
ws: false,
//目标地址
target: 'http://localhost:8088',
//发送的请求头host会被设置target
changeOrigin: true,
//不重写请求地址
pathReWrite: {
'^/': '/'
}
};
// 在线聊天 代理
proxyObj['/ws'] = {
ws: true,
target: 'ws://localhost:8088'
}
module.exports = {
publicPath: '/', //基本路径
outputDir: 'dist', //打包的包文件名
assetsDir: 'static', //css、js、img静态资源存放文件夹
lintOnSave: false, //是否在保存的时候使用 `eslint-loader` 进行检查。默认true
runtimeCompiler: false, //是否使用包含运行时编译器的 Vue 构建版本。默认false
productionSourceMap: false,//生产环境不需要 source map,加速生产环境构建。默认true
devServer: {
host: 'localhost',
port: 8080,
proxy: proxyObj
}
};
重启服务器就能访问到后端 http://localhost:8088 ;ws://localhost:8088 啦
后端设置
/**
* 设置跨域请求
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*") //允许
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}