Springboot React跨域 详解Springboot+React项目跨域访问问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Springboot React跨域 详解Springboot+React项目跨域访问问题

https://blog.csdn.net/hanziang   2021-03-30 我要评论

一、开发环境

  • 框架:springboot 1.5.10.RELEASE
  • 开发工具:IDEA
  • JDK:1.8
  • 前端框架:React 15.6.1
  • 浏览器:Chrome浏览器

二、跨域问题

本地使用ajax访问localhost:8080端口时报错:

Failed to load http://localhost:8080/test/test.do: No ‘Access-Control-Allow-Origin' header is present on the requested resource. Origin ‘null' is therefore not allowed access.

React与Springboot前后端分离,React端口为3000而Springboot端口为8080,跨端口访问用寻常的ajax是无法跨域访问的。

什么是跨域?

当客户端向服务器发起一个网络请求,url会有包含三个主要信息:协议(protocol),域名(host),端口号(port)。当三部分都和服务器相同的情况下,属于同源。但是只要有一个不同,就属于构成了跨域调用。会受到同源策略的限制。

同源策略限制从一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的关键的安全机制。浏览器的同源策略,出于防范跨站脚本的攻击,禁止客户端脚本(如 JavaScript)对不同域的服务进行跨站调用(通常指使用XMLHttpRequest请求)。

三、解决方法

(1)java后端过滤器实现cros:

在后端配置过滤器CrosFilter

public class CorsFilter implements Filter {

  public void init(FilterConfig filterConfig) throws ServletException {
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    httpResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");//设置允许跨域的域名,需要发送cookie信息,所以此处需要指定具体的域名,
    httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    httpResponse.setHeader("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST");//允许跨域的请求方式
    /**
     * ajax请求的时候如果带有xhrFields:{withCredentials:true},
     * 那么服务器后台在配置跨域的时候就必须要把Access-Control-Allow-Credentials这个请求头加上去
     */
    httpResponse.setHeader("Access-Control-Allow-Credentials", "true");//允许发送Cookie信息
    httpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP 1.1.
    httpResponse.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. response.setHeader("Expires", "0");
    chain.doFilter(request, response);
  }

  public void destroy() {
    // TODO Auto-generated method stub
  }
}

参考:跨域资源共享 CORS 详解——阮一峰

(2)使用代理服务器跨域访问:

在dev.js中配置

devServer: {
      port: '3000',//开发端口
      host: '127.0.0.1',//主机地址
      historyApiFallback: false,
      disableHostCheck: true,
      noInfo: false,
      stats: 'minimal',
      inline: true,
      //开启服务器的模块热替换(HMR)
      hot: true,
      // 和上文 output 的“publicPath”值保持一致
      publicPath: context,
      proxy: {
        '/mytest/*': {
          target: "http://localhost:8080",//对应后端端口
          secure: false,
          changeOrigin: true
        }//如果Controller的Requestmapping有多个这里也要对应多个
        ,'/test/*': {
          target: "http://localhost:8080",
          secure: false,
          changeOrigin: true
        }
      }

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们