第一种方法

在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);
} @Bean
public 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 { @Override
public 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. 前后端分离框架前端react,后端springboot跨域问题分析

    前后端分离框架前端react,后端springboot跨域问题分析 为啥跨域了 前端react的设置 springboot后端设置 为啥跨域了 由于前后端不在一个端口上,也是属于跨域问题的一种,所以必 ...

  2. springmvc springboot 跨域问题(CORS)

    官方文档:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html springmvc s ...

  3. 两种解决springboot 跨域问题的方法示例

    两种解决springboot 跨域问题的方法示例,哪种方法看情况而定,自己选择.社会Boolean哥,人狠话不多,直接上代码. 第一种实现方式:       此种方式做全局配置,用起来更方便,但是无法 ...

  4. SpringBoot跨域问题

    1.先来说说跨域原理: 跨域原理简单来说就是发起跨域请求的时候,浏览器会对请求域返回的响应信息检查HTTP头,如果Access-Control-Allow-Origin包含了自身域,则允许访问,否则报 ...

  5. SpringBoot跨域小结

    前言:公司的SpringBoot项目出于某种原因,经常样处理一些跨域请求. 一.以前通过查阅相关资料自己写的一个处理跨域的类,如下. 1.1首先定义一个filter(拦截所有请求,包括跨域请求) pu ...

  6. springboot跨域请求

      首页 所有文章 资讯 Web 架构 基础技术 书籍 教程 Java小组 工具资源 SpringBoot | 番外:使用小技巧合集 2018/09/17 | 分类: 基础技术 | 0 条评论 | 标 ...

  7. 关于解决Springboot跨域请求的方法

    前言 最近在项目中,由于前后分离,前台项目和后台项目部署的不在一台服务器,就产生了跨域的问题,特此记录下 正文 正常情况下,如果提示: 就可以判断是没有解决跨域的问题了. 在SSM中,我曾经这样解决过 ...

  8. springboot跨域请求设置

    当它请求的一个资源是从一个与它本身提供的第一个资源的不同的域名时,一个资源会发起一个跨域HTTP请求(Cross-site HTTP request).比如说,域名A ( http://domaina ...

  9. springboot 跨域

    参考: https://blog.csdn.net/qq779446849/article/details/53102925 https://blog.csdn.net/wo541075754/art ...

  10. Springboot跨域 ajax jsonp请求

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

随机推荐

  1. Docker原理:Cgroup

    目录 Cgroup 主要功能 术语 参考 Cgroup 全称Linux Control Group, 是Linux内核的一个功能,用来限制.控制与分离一个进程组群的资源(如CPU.内存.磁盘输入输出等 ...

  2. kong插件Prometheus+grafana图形化展示

    目录 1. 准备工作 3. 为kong添加 prometheus插件 4. 打开kong的metrics支持 4. 配置prometheus.yml添加kong提供的数据信息 5. 在 Grafana ...

  3. Js中关于构造函数,原型,原型链深入理解

    在 ES6之前,在Javascript不存在类(Class)的概念,javascript中不是基于类的,而是通过构造函数(constructor)和原型链(prototype chains)实现的.但 ...

  4. AspNetCore&MassTransit Courier实现分布式事务

    在之前的一篇博文中,CAP框架可以方便我们实现非实时.异步场景下的最终一致性,而有些用例总是无法避免的需要在实时.同步场景下进行,可以借助Saga事务来解决这一困扰.在一些博文和仓库中也搜寻到了.Ne ...

  5. 关于 IPv6 国家有大动作啦!快来瞅瞅行动计划都说了什么~

    随着进入三伏天开始,杭州就像突然被丢上了炭火炉,没有空调的高温厕所,彻底断绝了二狗子带薪摸鱼的快乐.深感绝望的二狗子只能痛苦地把自己的摸鱼地点改成了空调大开的零食角."哎,真的很不喜欢零食角 ...

  6. matlab——线性规划

    @ 目录 前言 一.基本概念 二.matlab实现 1.常用函数 2.常见变形 参考书目 前言 线性规划是数学规划中的一个重要分支,常用于解决如何利用现有资源来安排生产,以取得最大经济效益的问题.本文 ...

  7. java String转List<Device>集合

    // 从Redis中获得正常设备的数量 String success = redisService.get(RedisKey.CULTIVATION_RECORD_SUCCESS); //建立一个li ...

  8. python调用接口方式

    python中调用API的几种方式: - urllib2- requests 一.调用别人的接口 案例1.urllib2 import urllib2, urllib github_url ='htt ...

  9. nacos Failed to obtain JDBC Connection 连接异常

    在conf/目录下,将application.properties.example 改名为bootstrap.properties 将连接数据库信息添加到末尾 # db mysql spring.da ...

  10. 【奇妙的JavaScript】# 1

    奇妙的JavaScript 本专题整理了一些JavaScript的怪异行为,大部分都是选择题,题目都是简单的表达式.可以测试你有多了解 JavaScript,拓宽你的认知边界! 该专题计划每周更新1- ...