Java uses nginx to implement cross-domain requests

Not much to say, just go to the code

1.nginx.conf configuration file

underscores_in_headers on;
server {
    listen   80;
    server_name  localhost;
    location / {
        root   html;
        index  index.html index.htm;
		proxy_pass   http://192.168.0.192:8081/;
		if ($request_method = 'OPTIONS') {  
			add_header Access-Control-Allow-Origin *;  
			add_header Access-Control-Allow-Headers  Content-Type,session_id,x-requested-with;  
			add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,PATCH,OPTIONS;  
		return 200;  
		}
 }

Among them, Content-Type, session_id is to put the value of session_id in the request header, which is mainly for systems with login permission control, so that the token can be passed in. The specific situation depends on the actual project requirements. Of course, when java sends an Ajax request, session_id needs to be assigned, the code is as follows:

 $.ajax({
	url:$("#hostPort", parent.document).val()+'/business/api/face/update',
	type : "post",
	beforeSend : function(XMLHttpRequest) {
				XMLHttpRequest.setRequestHeader("session_id", $(
						"#session_id", parent.document).val());
	},
	dataType : 'json', //服务器返回的格式,可以是json或xml等
	success : function(result) {
	}
 });

In order to enable underscore support for headers under http, you need to add the underscores_in_headers on configuration in nginx

2.java code

public static void response(HttpServletResponse response , Object object){
	try {
	response.addHeader("Access-Control-Allow-Origin", "*");            //JS 跨域访问
    response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    response.setCharacterEncoding("utf-8");
	response.getWriter().print(JSON.toJSONString(object,SerializerFeature.DisableCircularReferenceDetect));
	} catch (IOException e) {
		e.printStackTrace();
	}
}

Guess you like

Origin blog.csdn.net/xzw12138/article/details/86495905