第一种方法

在Controller类或方法上加上@CrossOrigin元注解

package com.wzq.test.action;import com.wzq.utils.BatchDownFilesUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;/*** @description: 测试Controller* @author: Wzq* @create: 2019-11-25 10:19*/
@CrossOrigin(origins = "*")
@RestController
@RequestMapping(value = "test")
public class TestController {@RequestMapping(value = "/test.do")public String test(){return "test";}}

这种方式对于整个项目都要跨域,那么每个类上都要加@CrossOrigin元注解,比较麻烦,下面讲解下全局跨域配置。

第二种 拦截器的方式

package com.wzq;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;@SpringBootApplication
public class MyprojectApplication {public static void main(String[] args) {SpringApplication.run(MyprojectApplication.class, args);}@Beanpublic FilterRegistrationBean corsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();CorsConfiguration config = new CorsConfiguration();config.setAllowCredentials(true);config.addAllowedOrigin("*");config.addAllowedHeader("*");config.addAllowedMethod("*");source.registerCorsConfiguration("/**", config); // CORS 配置对所有接口都有效FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));bean.setOrder(0);return bean;}}

第三种 集成WebMvcConfigurerAdapter类重写 addCorsMappings方法

package com.meeno.wzq;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/*** @Auther: Wzq* @Date: 2019/4/11 18:30* @Description: 天青色等烟雨,而我在等你.. -- CORSConfiguration*/
@Configuration
public class CORSConfiguration  extends WebMvcConfigurerAdapter {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedMethods("*").allowedOrigins("*").allowedHeaders("*");super.addCorsMappings(registry);}
}

第三种有个问题,session无法共享!

第四种 使用nginx代理 把前端项目和服务端api接口地址,保持在同一个ip和端口中

完整的nginx配置如下:


#user  nobody;
worker_processes  1;#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {worker_connections  1024;
}http {include       mime.types;default_type  application/octet-stream;#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '#                  '$status $body_bytes_sent "$http_referer" '#                  '"$http_user_agent" "$http_x_forwarded_for"';#access_log  logs/access.log  main;sendfile        on;#tcp_nopush     on;#keepalive_timeout  0;keepalive_timeout  65;#gzip  on;server {listen       20684;server_name  inner.meeno.net;#charset koi8-r;#access_log  logs/host.access.log  main;location /trainsys {#root   html;#index  index.html index.htm;client_max_body_size 100000m;proxy_set_header Host $host;proxy_set_header X-Real-Ip $remote_addr;proxy_set_header X-Forwarded-For $remote_addr;proxy_pass http://inner.meeno.net:20681/trainsys/;}location /dist {root   E:\svnResourse\program\webTwo\sysBankAdmin-Vue;index  index.html index.htm;}#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   html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {#    proxy_pass   http://127.0.0.1;#}# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000##location ~ \.php$ {#    root           html;#    fastcgi_pass   127.0.0.1:9000;#    fastcgi_index  index.php;#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;#    include        fastcgi_params;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one##location ~ /\.ht {#    deny  all;#}}# another virtual host using mix of IP-, name-, and port-based configuration##server {#    listen       8000;#    listen       somename:8080;#    server_name  somename  alias  another.alias;#    location / {#        root   html;#        index  index.html index.htm;#    }#}# HTTPS server##server {#    listen       443 ssl;#    server_name  localhost;#    ssl_certificate      cert.pem;#    ssl_certificate_key  cert.key;#    ssl_session_cache    shared:SSL:1m;#    ssl_session_timeout  5m;#    ssl_ciphers  HIGH:!aNULL:!MD5;#    ssl_prefer_server_ciphers  on;#    location / {#        root   html;#        index  index.html index.htm;#    }#}}

主要看这段:


listen       8080; #端口
server_name  127.0.0.1;#ip或域名#服务端api基地值location /trainsys { #root   html;#index  index.html index.htm;client_max_body_size 100000m;proxy_set_header Host $host;proxy_set_header X-Real-Ip $remote_addr;proxy_set_header X-Forwarded-For $remote_addr;proxy_pass http://inner.meeno.net:20681/trainsys/;}#web端项目映射地址location /dist {root   E:\svnResourse\program\webTwo\sysBankAdmin-Vue;index  index.html index.htm;}

个人微信公众,经常更新一些实用的干货:架构师与哈苏

SpringBoot跨域相关推荐

  1. springBoot跨域注解@CrossOrigin

    Spring Framework 4.2 GA为CORS提供了第一类支持,使您比通常的基于过滤器的解决方案更容易和更强大地配置它.所以springMVC的版本要在4.2或以上版本才支持@CrossOr ...

  2. springboot 跨域配置cors

    撸了今年阿里.头条和美团的面试,我有一个重要发现.......>>> 1 跨域的理解 跨域是指:浏览器A从服务器B获取的静态资源,包括Html.Css.Js,然后在Js中通过Ajax ...

  3. Springboot跨域 ajax jsonp请求

    SpringBoot配置: <dependency><groupId>org.springframework.boot</groupId><artifactI ...

  4. SpringBoot跨域请求

    在软件开发过程中,尤其是现在的前后端分离开发,跨域请求是很普通的事情,我这个只是简单的将所有的跨域请求都接受,如若有大佬有更好的解决方案欢迎分享 问题: 在请求的时候,前端使用js进行ajax请求未能 ...

  5. Vue + SpringBoot跨域

    Vue设置 1.在项目根目录创建文件vue.config.js module.exports = {devServer: {proxy: {'/api': {target: 'http://zlf.p ...

  6. SpringBoot 跨域请求

    问题 @RequestMapping("/demo") @RestController public class CorsTestController {@GetMapping(& ...

  7. 【跨域】跨域原理 + springboot跨域配置(万能版)

    先上配置 这个配置是个万能药,配上之后就没有任何跨域问题了. @Configuration public class MvcConfig implements WebMvcConfigurer {@B ...

  8. 解决springboot跨域问题No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

    文章目录 1.问题描述 2.问题产生 3.解决方案 1. 在WebMvcConfig添加(推荐使用) 2.直接采用SpringBoot的注解@CrossOrigin 1.Controller层在需要跨 ...

  9. 【精品】SpringBoot跨域请求 解决方案汇总

    代码下载地址:本博客示例代码 第一步:创建前端页面 项目结构图 页面代码 <!DOCTYPE html> <html lang="zh-cn"> <h ...

  10. springboot 跨域解决方案

    跨域解析:当一个请求url的协议.域名.端口三者之间任意一个与当前页面url不同即为跨域 跨域原理:无论哪种方案,最终目的都是修改响应头,向响应头中添加浏览器所要求的数据,进而实现跨域 跨域访问的弊端 ...

最新文章

  1. 第四次人口普查数据_第七次人口普查预估:单身男性比女性多3000万?你在其中吗?...
  2. unix 存储空间不足 无法处理此命令_大数据分析命令行使用教程
  3. 存储过程学习三(创建存储过程实例)
  4. 爬取了京东商城上的部分手机评论数据,仅供学习使用
  5. Spring IoC 源码系列(四)bean创建流程与循环依赖问题分析
  6. windows下oracle数据库自动备份脚本
  7. mysql恢复主服务器_MySQL 5.6主从复制第二部分[恢复某一台从服务器]
  8. thymealf 高级用法_Thymeleaf
  9. C++教程:C++开发语言可以做些什么?
  10. CentOS / RHEL Cachefiles 加速网络文件系统NFS访问速度
  11. 混合编程:VS2017 C++调用Python3.X类/对象/函数笔记【Windows】
  12. python打包成exe
  13. phpstudy2018启动关闭_phpstudy2018搭建Apache https 开启php_openssl
  14. 网络文学格局已定?未必
  15. html鼠标悬停box变色,ToolTip鼠标悬停的使用
  16. 概率密度函数曲线及绘制
  17. Jaspersoft Studio 创建简单报表
  18. boost哪些库需要编译
  19. 大数据开发面试题总结-超详细
  20. 利用计算机引号作用,计算机双引号怎么打出来

热门文章

  1. 第一轮通知 | 2022年中国生物物理学会肠道菌群分会年会暨“崂山论肠菌”学术论坛...
  2. Nature子刊:利用转细菌基因植物修复土壤有毒污染物!
  3. Python使用numpy包编写自定义函数计算平均绝对误差(MAE、Mean Absolute Error)、评估回归模型和时间序列模型、解读MAE
  4. Python使用matplotlib可视化多个不同颜色的折线图、通过FontProperties为可视化图像配置中文字体可视化、并指定字体大小
  5. R语言ggplot2可视化分面图(faceting)、可视化分面条形图(facet_wrap bar plot)、使用strip.text函数自定义分面图每个分面标题条带strip的大小(cutomi
  6. R语言ggplot2可视化:ggplot2可视化分组散点图并使用geom_smooth函数在散点图图中为不同的散点簇添加对应的回归曲线
  7. python使用fpdf生成发票格式的pdf文件包含:文字、图片logo、表格、条形码等;
  8. R语言Logistic逐步回归模型案例:分析与冠心病有关的危险因素
  9. 什么是维度诅咒?如何评估降维算法在当前任务数据集上的效果?
  10. python模块datetime将字符串转换为日期