java使用nginx实现跨域请求

导读:本篇文章讲解 java使用nginx实现跨域请求,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

不多说,直接上代码

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/12934.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!