一、首先解决本地开发环境的跨域
1. springboot配置全局跨域
// 全局跨域,添加所有的mapping,methods,origins等
package com.zty.springboot01login.Config;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
@EnableWebMvc
public class CORSConfiguration extends WebMvcConfigurationSupport {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedOrigins("*")
.allowedHeaders("*").
allowCredentials(true).
exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L);
super.addCorsMappings(registry);
}
}
2. vue配置代理
在config/index.js中配置代理,让vue的所有http请求都跨域,在文件中写一个proxyObj,http所有请求都指向后端的端口,此处为8800
let proxyObj = {};
proxyObj['/ws'] = {
ws: true,
target: "ws://localhost:8800"
};
proxyObj['/'] = {
ws: false,
target: 'http://localhost:8800',
changeOrigin: true,
pathRewrite: {
'^/': ''
}
}
3. 开发环境测试
我的开发环境为windows10,为了和ubuntu环境一致,也使用nginx
- 先分别启动vue dev和springboot,测试两边能够跨域
- 然后启动vue打包dist,放到ngixn的文件夹下,启动nginx,测试能否与后端跨域
- 配置nginx的config如下,所有的api请求都跨域
server {
listen 8081;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html\dist;
index index.html index.htm;
}
location /api/ {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
rewrite /api/(.*) /$1 break;
# 后端服务地址
proxy_pass http://localhost:8800;
}
二、 解决ubuntu部署nginx的跨域
- 打包vue为dist放到ubuntu
- 打包idea下的项目,使用maven的package打包为jar,也放到ubuntu
- 配置nginx/default,把root改为dist目录,然后添加一个localtion
location /api/ {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
rewrite /api/(.*) /$1 break;
# 后端服务地址
proxy_pass http://localhost:8800;
}
- 启动nginx,通过ip和端口访问即可