欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Springboot+React項目跨域訪問問題

 更新時間:2023年12月07日 10:39:03   作者:PY教義  
這篇文章主要介紹了詳解Springboot+React項目跨域訪問問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

一、開發(fā)環(huán)境

  • 框架:springboot 1.5.10.RELEASE
  • 開發(fā)工具: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是無法跨域訪問的。

什么是跨域?

當客戶端向服務器發(fā)起一個網(wǎng)絡請求,url會有包含三個主要信息:協(xié)議(protocol),域名(host),端口號(port)。當三部分都和服務器相同的情況下,屬于同源。但是只要有一個不同,就屬于構(gòu)成了跨域調(diào)用。會受到同源策略的限制。

同源策略限制從一個源加載的文檔或腳本如何與來自另一個源的資源進行交互。這是一個用于隔離潛在惡意文件的關(guān)鍵的安全機制。瀏覽器的同源策略,出于防范跨站腳本的攻擊,禁止客戶端腳本(如 JavaScript)對不同域的服務進行跨站調(diào)用(通常指使用XMLHttpRequest請求)。

三、解決方法

(1)java后端過濾器實現(xiàn)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");//設置允許跨域的域名,需要發(fā)送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");//允許發(fā)送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',//開發(fā)端口
      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
        }
      }

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論