温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-27 12:48:32 来源:脚本之家 阅读:280 作者:https://blog.csdn.ne 栏目:编程语言

一、开发环境

  • 框架: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
        }
      }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI