3gipnet 发表于 2017-2-24 11:37:30

关于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));
}
return str.join('&');
}
}).success(function (data) {
if (data.status == 1) {
alert("登录失败");
} else {
alert("登录成功");
}
});
页: [1]
查看完整版本: 关于AngularJS中$http跨域 与 nodejs接收跨域请求(使用express-session,body-parser)的设置