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

前端测试代码:





测试ajax和跨域访问




	


测试结果:

Nginx(5) 配置Ajax跨域访问_第1张图片


你可能感兴趣的:(配置,故障,网络,nginx,分布式,http)