当前位置: 移动技术网 > IT编程>开发语言>Java > 详解Springboot+React项目跨域访问问题

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

一、开发环境

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网