以springboot+vue为实例实际解决浏览器跨域问题
浏览器跨域之前的的文章有详细的阐述,这里只讲解跨域问题如何处理
前端请求:http://www.chenalibrary.work/ -这里实际请求地址http://47.102.142.203:80
服务器地址:http://47.102.142.203:8089
解决跨域我这里提供三种解决方案
方案一:vue中webpack
这种方案的有一个局限性—vue在本地调用
本地服务器或者远端服务器才可以解决跨域
用脚手架创建Vue项目后 找到config/index.js
文件在里面找到proxyTable
这个属性,默认是一个空对象
proxyTable: {
'/api': {
target: 'http://47.102.142.203:8089/', // api线上地址
changeOrigin: false, // 如果是 https ,需要开启这个选项
secure: false, // 是否允许跨域 - 这里肯定是true
pathRewrite: { // 重写url
'^/api': ''
// 这是代理后我们需要的在我们的我们前端请求上加上/api
// 前端请求地址:http://localhost:8989/api/user/login
// 实际请求地址:http://47.102.142.203:8089/user/login
}
}
},
方案二:Nginx配置代理转发解决跨域
首先找到的我们安装nginx配置文件的目录 一般都在根目录 /etc/nginx/conf.d/default.conf
default.conf
:此文件是默认存在可以删除 然后创建自己的配置文件,也可在上面修改,我这里是直接在上面的修改,不建议这种操作,你可以在创建一个xxx.conf文件,然后将listen后的80端口改为自己需要监听的端口,其他的和我的配置文件保持一样,或者不改也可以这里用到了vim 命令 教程:https://www.runoob.com/linux/linux-vim.html
这里贴一下我的命令:
1、vim命令打开default.conf
vim /etc/nginx/conf.d/default.conf
2、按一下键盘按键 i 键将default.conf 文件改为可编辑状态
3、修改完毕后按一下esc键退出编辑
4、shift+:键你可以看到如图所示区域(最底部)
5、在冒号后输入wq 在按一下enter键保存并退出
Nginx配置文件
server {
listen 80; # nginx-监听端口
server_name localhost; # 服务器名
# 第一个location 配置的是前端页面资源
# root 前端页面目录 index.html 根目录/dist/index.html
# 这里意思-当请求服务的80端口时请求的到的资源是/dist/index.html资源
location / {
root /dist;
index index.html index.htm;
}
# 浏览器请求api资源nginx转发
# 当监听到 ![前后端分离nginx转发流程图.png](https://upload-images.jianshu.io/upload_images/25278837-538c240f9aec66cb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
/api/user/login请求时 nginx将转发到 http://47.102.142.203:8089/user/login
location /api {
proxy_pass http://47.102.142.203:8089/;#后端部署上线后的地址,注意端口后面的'/'要加上,不然会404
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_redirect off;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
请求地址截图
ps:centos中默认http https协议请求的事80端口所以我这里没有输入端口如果都是本地这里需要输入端口
个人理解Nginx转发流程
方案三:java端服务器处理
1、实现
WebMvcConfigurer
接口重写addCorsMappings
方法
package com.chenc.mumu.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 解决可跨域
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的路径
registry.addMapping("/**")
//设置允许跨域请求的域名
//当**Credentials为true时,**Origin不能为星号,需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
.allowedOrigins("http://localhost:8989/")
//是否允许证书 不再默认开启
.allowCredentials(false)
//设置允许的方法
.allowedMethods("*")
//跨域允许时间
.maxAge(3600);
}
}
2、注解@CrossOrigin
Spring Framework 4.2 GA为CORS提供了第一类支持,使您比通常的基于过滤器的解决方案更容易和更强大地配置它。所以springMVC的版本要在4.2或以上版本才支持@CrossOrigin
这种用法暂时还没有研究透彻待后续更新