java使用nginx实现跨域请求

不多说,直接上代码

1.nginx.conf配置文件

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;  
		}
 }

其中Content-Type,session_id 是为了在请求头中放入session_id值,主要是针对有登陆权限控制的系统,方便将token传进去,具体情况看实际项目需求。当然,java发送Ajax请求时需要给session_id赋值,代码如下:

 $.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) {
	}
 });

为了在http下开启header的下划线支持,需要在nginx中添加underscores_in_headers on配置

2.java代码

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();
	}
}

猜你喜欢

转载自blog.csdn.net/xzw12138/article/details/86495905