1. 程式人生 > >Nginx(5) 配置Ajax跨域訪問

Nginx(5) 配置Ajax跨域訪問

配置nginx跨域訪問的好處是可以不修改後端程式碼

nginx只要在返回頭新增幾個header即可

add_header 'Access-Control-Allow-Headers' 'Content-Type';
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET';

具體nginx.conf的配置:

	upstream gao.com{
		server 192.168.4.199:8084 weight=1;
		server 192.168.4.199:8085 weight=1;
		server 127.0.0.1:8084 weight=1;
	}
    server {
        listen       80;
        server_name  localhost;
        location / {
            proxy_pass http://gao.com;
            proxy_redirect default;
			proxy_connect_timeout 1s;
			proxy_read_timeout 1s;
			proxy_send_timeout 1s;
			add_header 'Access-Control-Allow-Headers' 'Content-Type';
			add_header 'Access-Control-Allow-Origin' '*';
			add_header 'Access-Control-Allow-Methods' 'GET';
        }
		

後端測試程式碼:

@RestController
public class RedisController implements CommandLineRunner {
	@RequestMapping("/test")
	public Object test(String name, String no, HttpServletRequest req) {
		String sid = req.getSession().getId();
		return String.valueOf(i) + System.getProperty("user.dir") + o.name+",sessionid="+sid;
	}
}

前端測試程式碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>測試ajax和跨域訪問</title>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
    $.ajax({
        type: "POST",
       /*  dataType: 'json', */
        url: "http://192.168.4.200/redis/test",
        data: {
            openid: "testajax",
            sign: "testsign"
        },
        success: function(data) { 
        	console.log(data)
        	$('.detial_f').show().html(data);
        },
        error: function() {
            alert("fail!!!,請重新整理再試!");
        }
    });
});
</script>
<body>
	<div class="button_control">
		<button onClick ="getpara()" class="button_start">按鈕</button>
	</div>
	<div class="test">
		<p class="detial_f"></p>
	</div>
</body>
</html>

測試結果: