关于AngularJS中$http跨域 与 nodejs接收跨域请求(使用express-session,body-parser)的设置...

1.跨域的服务端设置:

使用express挂载跨域响应中间件

app.all("*", function (req,res,next) {

let allowedOrigins = [
"http://192.168.1.101:3000",
"http://105.123.123.123:3000"
];
 // 这里是允许跨域的的domain列表

let origin = req.headers.origin;
if(allowedOrigins.indexOf(origin) > -1){
res.setHeader('Access-Control-Allow-Origin', origin);
}

res.header('Access-Control-Allow-Credentials', true);// Allow Cookie
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
next();
});

2.$http的general用法:

$http({
    url:"http://localhost:3005/login",
    method:"POST",
    withCredentials: true,
    // 允许发送Cookie
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: {
        username:$scope.username,
        password:$scope.password
    },
    // 使数据匹配body-parser的形式,否则会解析错误拿不到数据,如果不用这一个方法,数据会被解析成一个{key:value}的json,key是整个数据的字符串,而value是空.
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj){
            str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
        }
        return str.join('&');
    }
}).success(function (data) {
    if (data.status == 1) {
        alert("登录失败");
    } else {
        alert("登录成功");
    }
});

 

转载于:https://www.cnblogs.com/Totooria-Hyperion/p/5565319.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值