目前项目中的前端页面还不是很多,打算进行前后端解耦,把页面拆出来放到nginx中,页面上通过异步请求接口获取数据,再进行页面渲染,使用nginx的反向代理机制可以解决跨域问题

WHAT ?跨域问题

页面资源与API接口不在同一个IP,或域名,端口时,所进行的访问都是跨域的,而浏览器为了安全问题都是限制了跨域访问,不允许跨域请求资源

常见的跨域解决方案

目前来讲没有不依靠服务器端来跨域请求资源的技术

  • jsonp 需要目标服务器配合一个callback函数。

  • window.name+iframe 需要目标服务器响应window.name。

  • window.location.hash+iframe 同样需要目标服务器作处理。

  • html5的 postMessage+ifrme 这个也是需要目标服务器或者说是目标页面写一个postMessage,主要侧重于前端通讯。

  • CORS 需要服务器设置header :Access-Control-Allow-Origin。

  • nginx反向代理,不需要目标服务器配合,只需要搭建一个nginx服务器,用于转发请求。

nginx反向代理解决跨域问题

nginx.conf

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / { #所有以/开头的地址,实际上是所有请求
        root   html; #去请求../html文件夹里的文件,其中..的路径在nginx里面有定义
        index  index.html index.htm;  #首页响应地址
    }

server代表启动的一个服务,location 是一个定位规则。

 location是nginx用来路由的入口,其实就是要在location里面实现反向代理。

ajax 部分的代码片段:

    // 获取接口数据,并渲染
    qrCode.shuffle = function () {
       var uid = getUrlParam("uid");
    //var url = "http://api.xxx/qr/profile?uid=";
    var proxyurl = "/proxy/html/qr/profile";
    var allType = $("#allType").val();
$.ajax({
    url: proxyurl,
    async: true,
    type: "GET",
    data: {
        "uid": uid,
    },
    dataType: "json",
    timeout: 1000,
    success: function (data) {

        var userInfo = data;
        // 用户昵称
        $("#name").append(userInfo.nickName);
        // 用户性别图片
        $("#sex").attr("src", "img/" + userInfo.sex);
        // BluId
        $("#idnumber").append(userInfo.userNum);
    },
})
};

如果通过 url = “http://api.xxx/qr/profile?uid=XX" 访问接口,必然会