react+spring 記錄跨域問題的解決方案

來源:互聯網
上載者:User

react 跨域訪問後台,預設是有跨域問題,並且火弧和Google瀏覽器,對跨域問題展示還不一樣.

Google瀏覽器如:

此處狀態是200,然而在Response卻沒有任何資訊,如

 

然而火弧瀏覽器,對該問題的描述,就清淅得多,

火弧瀏覽器告訴我們,跨域了,關於react跨域的文章,網上也有相關文章,搜尋到的方法,大約都是如下解決方式:

如果你是通過creat-react-app構建的項目,請在package.json檔案中的根目錄下,添加"proxy": "http://api.xxxx.com",如果你的項目,需要調用多個不同ip的介面,請使用如下配置:

"proxy": {        "/api/RoomApi": {          "target": "http://open.douyucdn.cn",          "changeOrigin":true        },        "/api/v1":{          "target":"http://capi.douyucdn.cn",          "changeOrigin":true        }      }

對於antd-pro的項目,需要在package.json的同等目錄下添加.roadhogrc檔案,具體代碼如下:

    {      "entry": "src/index.js",      "extraBabelPlugins": [        "transform-runtime",        "transform-decorators-legacy",        "transform-class-properties",        ["import", { "libraryName": "antd", "libraryDirectory": "es", "style": true }]      ],      "env": {        "development": {          "extraBabelPlugins": [            "dva-hmr"          ]        }      },      "externals": {        "g2": "G2",        "g-cloud": "Cloud",        "g2-plugin-slider": "G2.Plugin.slider"      },      "ignoreMomentLocale": true,      "theme": "./src/theme.js",      "proxy": {        "/api": {          "target": "http://api.xxxx.com/",          "changeOrigin": true        }      }    }

配置完成後,再次提供者,還是出現一樣的跨域問題,既然recat的配置,未解決跨域問題,我就把思路轉到spring,在spring去處理跨域,在後端程式添加一個攔截器,

package com.gg.interceptor;import java.util.ArrayList;import java.util.List;import java.util.Vector;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;public class ProcessInterceptor implements HandlerInterceptor{    @Override    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler)            throws Exception {        // TODO Auto-generated method stub         // 指定白名單網域名稱   http://localhost:8000,http://localhost:8000        List<String> whileList  = new Vector<String>();         whileList.add("http://127.0.0.1:8000");        whileList.add("http://localhost:8000");        String clientIp = httpServletRequest.getHeader("origin");        boolean status = false;        for(String ip : whileList) {            if(clientIp!=null&&clientIp.equals(ip)) {                status = true;                break;            }        }        /**         * 網上解決方案是httpServletResponse.setHeader("Access-Control-Allow-Origin","*");設定後發現,還是不能處理跨域問題,需要指定某一個ip,如:http://127.0.0.1:8000           * */        httpServletResponse.setHeader("Access-Control-Allow-Origin",status?clientIp:null);          //回應標頭設定          httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");          //響應類型        httpServletResponse.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");          httpServletResponse.setHeader("X-Powered-By","Jetty");          httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");        String method= httpServletRequest.getMethod();          if (method.equals("OPTIONS")){              httpServletResponse.setStatus(200);              return false;          }            System.out.println(method+",status:"+status+",clientIp:"+clientIp);            return true;      }    @Override    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,            ModelAndView modelAndView) throws Exception {        // TODO Auto-generated method stub            }    @Override    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)            throws Exception {        // TODO Auto-generated method stub            }}

spring-servlet.xml配置如下:

<mvc:interceptors>         <bean class="com.gg.interceptor.ProcessInterceptor"></bean>     </mvc:interceptors>  

react用戶端代碼如下:

Model層js代碼:*login({ payload }, { call, put }){      let formData = new FormData();      formData.append("loginId",payload.loginId);//帳號      formData.append("passWord",payload.passWord);//密碼      const response = yield call(requestGuangGao, formData);       yield put({        type: 'changeLoginStatus',        payload: response,      });    },api層js代碼:export async function requestGuangGao(formData){  // let formData = new FormData();  // formData.append("loginId",params.loginId);  // formData.append("passWord",params.passWord);  console.log("requestGua   >url  :" );   return request('http://127.0.0.1:8080/guanggao/userController/login.do', {    method: 'POST',     mode: 'cors',     body:formData,  });   }

通過以下設定,react跨域問題就處理好了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.