nginx解决跨域问题

来源:互联网 发布:python的位运算作用 编辑:程序博客网 时间:2024/06/05 20:14

场景:通过localhost反向代理至本地tomcat中html页面,ajax调用第三方接口,产生跨域问题。

思路:

1.nginx和tomcat不能共用同一端口,url一样,端口不同,也是跨域。所以需要nginx将localhost代理到tomcat 8020端口。浏览器输入: http://localhost/web/login.html,实际访问:http://192.168.0.134:8020/web/html

2.html中调用接口代码如下:

$.ajax({
       url:"http://localhost/api/login,
       type:"get",
       async: false,
       data:{"loginName":loginName,"password":password,},
       success:function(data){
      alert(data);
       }
   });

根据配置,nginx将调用接口地址代理为:http://116.62.40.204:8080/api/login



以下是nginx.conf配置:

#user  nobody;
worker_processes  1;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    upstream tomcat {
      server 192.168.0.134:8020;
    }
    upstream api {
      server 116.62.40.204:8080;
    }
    server {
        listen       80;
        server_name  192.168.0.128;


        #charset koi8-r;


        #access_log  logs/host.access.log  main;

       location / {
          proxy_set_header  Host $host;
          proxy_set_header  X-Real-IP  $remote_addr;
          proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-For $remote_addr;
          proxy_pass http://tomcat;
          #expires 12h;
       }
       location /api/ {
          proxy_set_header  Host $host;
          proxy_set_header  X-Real-IP  $remote_addr;
          proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-For $remote_addr;
          proxy_pass http://api;
          #expires 12h;
       }
        #error_page  404              /404.html;


        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
0 0
原创粉丝点击