Nginx jquery跨域请求解决方案

Nginx jquery跨域请求解决方案

方案一:nginx配置

server {
    listen       88;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

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

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

    # 请求接口
    location /gateway/ {
        proxy_pass    http://192.168.10.107:8080/;
    }
}
http://chanpinxue.cn:8080/gateway/api/task.action 会直接转发到 http://192.168.10.107:8080/api/task.action

方案二:jquery前后端配置

1、前端

jQuery.ajax({
    url: "http://chanpinxue.cn:8080/index.action",
    type: "get",
    dataType: "jsonp",
    cache: false,
    //contentType: "application/json; charset=gbk",
    jsonpCallback: "callback",
    //xhrFields: {withCredentials: true},
    //crossDomain: true,
    success: function (data) {
    	alert(data);
    	//将数据转换成json类型,可以把data用alert()输出 查看结构
//var json = JSON.stringify(data);
//alert(data);
    }
});

2、后端

JSONObject objTask = new JSONObject();
obj.put("taskno", "sn0000001");
response.setHeader("Access-Control-Allow-Origin","*");

//response.getWriter().write("callback(" + objTask + ")");

out.print("callback(" + objTask + ")");

 

发表回复

您的电子邮箱地址不会被公开。