Solve cross-domain problems [separation of front-end and back-end, front-end uses axios]

Problem description:
Front-end URL: http://h5.xxx.com, back-end URL: http://gateway.yyy.com The
front-end uses axios to send ajax requests to the back-end, and the
back-end uses Spring Boot, which can be seen in the interceptor The session id of each request is different, and the "SESSIONID" parameter is included in the set-cookie of each response, obviously because the front-end does not pass the sessionid to the back-end through a cookie.


Solution Add to
front-end request:
  const obj = Object.assign({}, config, {
    headers,
    withCredentials: true,
    crossDomain: true,
  });


Backend Interceptor:
  HttpServletResponse servletResponse = (HttpServletResponse) response;
  servletResponse.setContentType("application/json; charset=utf-8");  
  servletResponse.setCharacterEncoding("UTF-8");
  // Special note: Access-Control-Allow-Origin value cannot be *, but should be a specific value
  // Otherwise, the cookie will not be passed
  // Here directly use request.getHeader("Origin"), in fact, the effect is basically the same as *
  servletResponse.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
  servletResponse.addHeader("Access-Control-Allow-Credentials", "true");
  servletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,Cookies");

  if (request.getHeader("Access-Control-Request-Method") != null
    && "OPTIONS".equals(request.getMethod())) {// CORS "pre-flight" request
    servletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    servletResponse.addHeader("Access-Control-Max-Age", "7200");
    servletResponse.setStatus(200);
    servletResponse.getWriter().write("OK");
    return;
  }


// Add 2018.03.30
There is still a big hole here. We still found that the session id is inconsistent every time when we tested the IOS WeChat public account, but the Android WeChat is OK.

Reason: When the h5 page accesses the gateway through ajax, the WeChat side of IOS cannot write cookies. However, if the gateway is accessed through the IOS WeChat browser normally, and the cookie is written normally, then the h5 page accesses the gateway through ajax, and the cookie of the gateway can be carried at this time (ie: the IOS WeChat browser is only valid for cross-domain cookies). read mode)

Therefore, just before the h5 page accesses the gateway (or before logging in), first point the location.href to the gateway in h5, and then redirect back by the gateway (at this time, the gateway's cookie has been written normally) The following Access can normally carry cookies


response.sendRedirect(request.getHeader("referer"));


References: https://blog.csdn.net/zhx19920405/article/details/51417250
Thanks for the solution shared by God

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326214439&siteId=291194637