前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Nginx 反向代理解决前后端联调跨域问题

Nginx 反向代理解决前后端联调跨域问题

作者头像
前端教程
发布2018-03-27 16:23:24
2.2K0
发布2018-03-27 16:23:24
举报
文章被收录于专栏:程序员IT圈程序员IT圈

keywords: Nginx反向代理 前后端联调 跨域


1.什么是跨域

跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。

所谓同源是指,域名,协议,端口都相同。浏览器执行javascript脚本时,会检查这个脚本属于哪个页面,如果不是同源页面,就不会被执行。

2.跨域的常见解决方法

目前来讲没有不依靠服务器端来跨域请求资源的技术   1. jsonp 需要目标服务器配合一个callback函数。   2. window.name+iframe 需要目标服务器响应window.name。   3. window.location.hash+iframe 同样需要目标服务器作处理。   4.html5的 postMessage+ifrme 这个也是需要目标服务器或者说是目标页面写一个postMessage,主要侧重于前端通讯。   5.CORS 需要服务器设置header : Access-Control-Allow-Origin。   6. nginx反向代理 这个方法一般很少有人提及,但是他可以不用目标服务器配合,不过需要你搭建一个中转nginx服务器,用于转发请求。

3.为什么要前后端分离

● 关注点分离 ● 职责分离 ● 对的人做对的事 ● 更好的共建模式 ● 快速的反应变化

淘宝前后端分离实践(http://2014.jsconf.cn/slides/herman-taobaoweb/#/)

4.nginx反向代理实现跨域和便捷的前后端联调

项目前后端分离后,前后端项目分开开发,尤其是单页面应用,前端代码会开启单独的服务器,若直接在前端项目中访问后端API,肯定会遇到因跨域不能访问的问题。

这时候,用nginx反向代理实现跨域,是最简单的跨域方式。只需要修改nginx的配置即可解决跨域问题,支持所有浏览器,支持session,不需要修改任何代码,并且不会影响服务器性能。

我们只需要配置nginx,在一个服务器上配置多个前缀来转发http/https请求到多个真实的服务器即可。这样,这个服务器上所有url都是相同的域名、协议和端口。因此,对于浏览器来说,这些url都是同源的,没有跨域限制。而实际上,这些url实际上由物理服务器提供服务。这些服务器内的javascript可以跨域调用所有这些服务器上的url。

将nginx目录下的nginx.conf修改如下,这里配置了两台server,如果只需一台,把其中一个server删除即可。之所以配置两台服务器,是前端可能同时在开发两个项目,或者同一个项目开发环境和生成环境各自开启一个服务,方便调试。

代码语言:javascript
复制
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


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;

    server {
        listen       9000;  #配置第一台服务器
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            #alias D:\\develop\\project1dir\\app\\; #配置别名到项目源代码目录,那么访问http://localhost:9000/即访问此目录
            # Frontend Server
            proxy_pass http://localhost:8001/;  #更聪明的做法是代理到前端服务器地址,比如gulp+browser-sync开启的服务器,能看到代码实时更新效果
        }

        location /api/ {
            rewrite ^/api/(.*)$ /$1 break;   #所有对后端的请求加一个api前缀方便区分,真正访问的时候移除这个前缀
            # API Server
            proxy_pass http://www.serverA.com;  #将真正的请求代理到serverA,即真实的服务器地址,ajax的url为/api/user/1的请求将会访问http://www.serverA.com/user/1
        }

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

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
    server {
        listen       9001;  #配置第二台服务器
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            #alias D:\\develop\\project1dir\\appDist\\;  #此文件夹可以是项目打包后的上线代码文件,也可以是第二个项目源代码文件
            # Frontend Server
            proxy_pass http://localhost:8002/;  #前端服务器地址,比如gulp+browser-sync开启的服务器,能看到代码实时更新效果
        }

        location /api/ {
            rewrite ^/api/(.*)$ /$1 break;  #所有对后端的请求加一个api前缀方便区分,真正访问的时候移除这个前缀
            # API Server
            proxy_pass http://serverB.com;  #将真正的请求代理到serverB,即真实的服务器地址,ajax的url为/api/user/1的请求将会访问http://www.serverB.com/user/1
        }

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

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }




    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-03-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员IT圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.什么是跨域
  • 2.跨域的常见解决方法
  • 3.为什么要前后端分离
  • 4.nginx反向代理实现跨域和便捷的前后端联调
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档