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'

When the credential mode of the request is 'include', the header in the response cannot be a wildcard '*' 

Maybe you have configured the cross-domain wildcard * to allow all domain names to cross-domain. Although this method is very insecure and will lead to some attacks, the reason for your configuration must first be to hope that it can work normally, but the above mentioned hint. The reason for the above prompt is that it is configured to require credential access when the ajax request is made, so you can no longer use the wildcard form, and you have to change it to a specific domain name.


2 If I don't add this configuration to ajax, does it mean that wildcards can be configured in the background? The answer is yes, but you will encounter the problem of session. The cookie requested each time will not be passed to the background, so that we cannot session Store some information, such as login information.
xhrFields: {
	 withCredentials: true
 },

refer to:

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=324552099&siteId=291194637