Solution to cross domain problem of react+spring records

Keywords: Javascript React Spring Java Google

react cross domain access background, default is cross domain problems, and fire arc and Google browser, cross domain problem display is not the same

Google browser is as follows:

The status here is 200, but there is no information in Response, as shown below

 

However, the description of this problem in fire arc browser is much clearer,

Fire arc browser tells us that there are cross domain and cross domain posts about react. There are also related posts on the Internet. The search methods are about the following solutions:

If you are building a project through the create react app, please add "proxy" in the root directory of the package.json file: "http://api.xxxx.com". If your project needs to call multiple different ip interfaces, please use the following configuration:

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

For the antd Pro project, you need to add the. roadhogrc file in the same directory of package.json. The specific code is as follows:

    {
      "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
        }
      }
    }

After the configuration is completed, the same cross domain problem still occurs when the interface is accessed again. Since the configuration of recat does not solve the cross domain problem, I will turn my thinking to spring to handle the cross domain problem in spring, and add an interceptor in the back-end program,

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 
        // Specify whitelist domain name   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;
            }
        }
        /**
         * The network solution is httpservletresponse.setheader ("access control allow origin", "*"); after setting, it is found that the cross domain problem cannot be solved. You need to specify an ip, such as:http://127.0.0.1:8000  
         * */
        httpServletResponse.setHeader("Access-Control-Allow-Origin",status?clientIp:null);  
        //Response header settings  
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");  
        //Response type
        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
        
    }

}

The configuration of spring-servlet.xml is as follows:

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

The react client code is as follows:

Model layer js Code:
*login({ payload }, { call, put }){
      let formData = new FormData();
      formData.append("loginId",payload.loginId);//Account number
      formData.append("passWord",payload.passWord);//Password
      const response = yield call(requestGuangGao, formData); 
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
    },

api layer js Code:
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,
  });   
}

With the following settings, the cross domain problem of react is solved.

Posted by d-m on Thu, 02 Jan 2020 14:46:36 -0800