web跨域问题

环境:

win7_x64旗舰版、Google Chrome-v44.0.2403.155、node-v0.10.29、express-v3.2.5、jQuery-v1.8.3

一、跨域GET:

客户端添加jQuery扩展函数getJSONP

$.getJSONP = function (url, data, callback) {
  $.getJSON(url + "?callback=?", data, callback);
};

调用:

$.getJSONP("www.xxx.com/test", {name1: param1, name2: param2}, function(data, status) {});

二、跨域POST:

客户端添加jQuery扩展函数postJSONP

$.postJSONP = function (url, data, callback) {
    $.ajax({
        type: "POST",
        url: url,
        data: d ata,
        success: callback,
        xhrFields: { withCredentials: true }, //将withCredentials属性设置为true,可以指定请求应该发送凭据(cookie、HTTP认证及客户端SSL证明等)
crossDomain: true
});
};

服务端添加响应函数:

router.post("/test", function (req, res) {
    res.setHeader("Access-Control-Allow-Credentials", true);
    if (req.headers.origin != undefined) {
        res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
    }
    res.jsonp(result);
//如果客户端不能接收返回数据,我们可以添加一个返回页面(login_result.html),并传递参数("status=true"),在返回的页面中添加js函数执行
  //res.redirect("./../login_result.html?status=true");
}

调用:

$.postJSONP("www.xxx.com/test", {name1: param1, name2: param2}, function(data, status) {});

三、跨域登录:

在html中添加

<iframe id="login" src="" style="display: none"></iframe>

在文档加载完成后,向跨域登录地址请求登录,登录成功后会获得Cookies

var param = document.location.search.substr(1); // 从当前页面获取登录信息,然后提交给跨域登陆地址
$("#login").attr("src", "www.xxx.com/login.html?"+ param);

最后:

在express-v3.2.5中,我们可以这样使用路由中间件app.use("/xxx", router.middleware),而在express-v4.x.x中z直接app.use("/xxx", router)就可以了。

原文地址:https://www.cnblogs.com/dongc/p/5147495.html