Cross-domain problems of front-end and back-end projects

      In doing front-end and back-end separation projects, we encountered cross-domain problems. Although there are many methods on the Internet, they are all one-sided, and the key information is not explained, which leads to some pitfalls. Now, the instructions and related codes for solving cross-domain problems in the front-end and back-end projects are posted for your reference.

       Because the jsonp method uses a too narrow domain, and only supports GET access, which is far from enough for normal projects, so this method is not used in the introduction. If you want to use this method, you can search for related applications online. illustrate.


1. Front-end project:


 1 jquery ajax:

    

		   $.ajax({
				 type : "get",
				 url : url,
				 crossDomain : true, // cross domain
//				 contentType: "application/json;charset=utf-8",
				 dataType:"json",
				 xhrFields: { //Access credentials
				 withCredentials: true
				 },
				 success : function (msg) {					
				 },
				 error:function(){
					 alert("An error has occurred!");
				 }
			 });

2 bootstrap table (partial)

// url : url,
//         ajaxOptions: {
// xhrFields: {//Access credentials
//                    withCredentials: true
// },// cross domain
//                crossDomain: true
//        },
//        method: 'GET',

2. Back-end projects

1 filter

package com.rz.commons.cross;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

/**
 * Cross-domain access
 */
@Component
public class CrossFilter implements Filter {
	
	private List<String> arrowOrigin=new ArrayList<>();
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
	    	
	        HttpServletRequest request = (HttpServletRequest) req;
	        HttpServletResponse response = (HttpServletResponse) res;
	        
	        String origin = request.getHeader("Origin");
//	        System.out.println("origin:"+origin);
	        response.setHeader("Access-Control-Allow-Origin",arrowOrigin.contains(origin)?origin:"");
	        response.setHeader("Access-Control-Allow-Methods", "*");//GET, POST, OPTIONS ...
	      //Cache the pre-detection results, within the set time, pre-detect the first time the request is sent, and then send the request directly
	        response.setHeader("Access-Control-Max-Age", "1728000");
	        response.setHeader("Access-Control-Allow-Credentials", "true");
	        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept , X-CSRF-TOKEN");
	        chain.doFilter(req, res);
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		String[] url=filterConfig.getInitParameter("arrowOriginUrl").split(",");
		arrowOrigin.addAll(Arrays.asList(url));
	}
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		arrowOrigin.clear();
	}
}
2 web.xml


<filter>
       <filter-name>cross</filter-name>
       <filter-class>com.hf.commons.cross.CrossFilter</filter-class>
       <init-param>
            <param-name>arrowOriginUrl</param-name>
            <param-value>http://localhost:8088</param-value>
       </init-param>
  </filter>
  <filter-mapping>
      <filter-name>cross</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>

注意事项:

1   header in the response must not be the wildcard '*' when the request's credentials mode is 'include'

当请求的凭证模式为'include'时,响应中的头部不能是通配符'*' 

也许你已经配置了跨域通配符*,允许所有域名跨域,虽这种方式是十分不安全的,会导致一些攻击,但你配置的原因肯定首先是希望它能正常工作的,但出现了上述提示。上述提示的原因是由于ajax请求的时候配置了它是需要凭证访问的,因此你不能再用通配符形式了,要改为具体的域名。


2  如果我ajax不加这个配置呢,是不是意味着可以在后台配置通配符了呢,答案是可以,但你会遇到session的问题,每次请求的cookie将无法传给后台,导致我们无法session存储一些信息,如登录信息。
 xhrFields: {
	 withCredentials: true
 },

参考:

https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
https://stackoverflow.com/questions/43114750/header-in-the-response-must-not-be-the-wildcard-when-the-requests-credentia
https://blog.csdn.net/taking_wang/article/details/77476864
https://www.cnblogs.com/ph121/p/6839424.html

https://blog.csdn.net/qq_37625033/article/details/57072944

http://www.it1352.com/634166.html


Guess you like

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