Nginx跨域配置

57 阅读1分钟

页面发起请求

$.ajax({
    type: "post",
    dataType: "json",
    data: {
      'parameter': JSON.stringify(data)
    },
    url: "http://www.binghe.com/apistest/test",
    async: flag,
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Content-Type", submitType.Content_Type);
        xhr.setRequestHeader("user-id", submitType.user_id);
        xhr.setRequestHeader("role-type", submitType.role_type);
        xhr.setRequestHeader("access-token", getAccessToken().token);
    },
    success: function(result, status, xhr){
        // todo               
    },
    error: function (e) {
        layerMsg('请求失败,请稍后再试')
    }
});

上述代码是页面上发起的Ajax请求,但是发生了跨域请求。

Nginx代理

server {
    location / {
        root   html;
        index  index.html index.htm;
        //允许cros跨域访问
        add_header 'Access-Control-Allow-Origin' '*';
    }
    
    //自定义本地路径
    location /apis {
        rewrite  ^.+apis/?(.*)$ /$1 break;
        proxy_pass   http://www.binghe.com;
    }
}
  1. add_header 'Access-Control-Allow-Origin' '*'

    • 设置一个响应头,允许所有来源的跨域请求。
  2. rewrite ^.+apis/?(.*)$ /$1 break

    • 使用正则表达式将请求中的/apis前缀删除,将剩余的字符串作为新的请求URL
  3. proxy_pass http://www.binghe.com

    • 处理后的请求转发到http://www.binghe.com一个后端服务器地址。

通过Nginx的代理,在客户端发送请求时,将url设置从http://www.binghe.com/apistest/test变为www.binghe.com/apis/apistest/test/

重新修改Ajax发送请求

$.ajax({
    type: "post",
    dataType: "json",
    data: {
        'parameter': JSON.stringify(data)
    },
    url: "http:www.binghe.com/apis/apistest/test",
    async: flag,
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Content-Type", submitType.Content_Type);
        xhr.setRequestHeader("user-id", submitType.user_id);
        xhr.setRequestHeader("role-type", submitType.role_type);
        xhr.setRequestHeader("access-token", getAccessToken().token);
    },
    success:function(result, status, xhr){
        // todo   
    },
    error:function (e) {
        layerMsg('请求失败,请稍后再试')
    }
});