gpt4 book ai didi

angularjs - CORS、AngujarJS 和 NodejsAPI 问题

转载 作者:搜寻专家 更新时间:2023-10-31 23:53:19 25 4
gpt4 key购买 nike

自从这个问题以来,我一直在抓头发。我已经使用 nodejs 构建了一个 restfull api,以将 json 数据提供给 angularjs 前端。我已经使用 Postdam chrome 扩展测试了我的 api,它可以正常工作,并将它与我正在构建的移动应用程序一起使用,它也可以正常工作。问题在于 Angular 。

当我尝试从 angujar 调用端点时,它会触发此错误

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://188.166.68.124' is therefore not allowed access. The response had HTTP status code 400.

Node.js 配置

var express             = require('express');
var app = express();
....
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morgan("dev"));

app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Headers');
next();
});

我的一个端点

router.route("/user/login")
.post(function(req,res){
var username = req.body.username;
var password = req.body.password;
... username and password comprobation and cleaning....
User.findOne({username: username},function(err,user){
if (err) res.send(err)
console.log(user);
if (user != null){
if (user.password == password)
res.send(user);
}
else{
res.send(403);
}
}
else{
res.send(403);
}
});
}
});

Angular 函数

this.login = function(user,password){
var datatoLogin = {"username":user,"password":password};
console.log("login function");
$http({
method:'POST',
data: $.param(datatoLogin),
headers:{'Access-Control-Allow-Origin': '*'}, // removing this has no effect
url: 'http://188.166.68.124:8080/api/user/login'
//withCredentials : true
}).success(function(data, status, headers, config){
console.log(data);
this.auth = true
//get data from data...
}).error(function(data,status,headers,config){
console.log("error getted");
console.log(data);
});
}

你们能帮我解决这个问题吗?

最佳答案

试试这个:

this.login = function(user,password){
var datatoLogin = {"username":user,"password":password};
console.log("login function");
$http({
method:'POST',
data: $.param(datatoLogin),
headers:{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, // removing this has no effect
url: 'http://188.166.68.124:8080/api/user/login'
//withCredentials : true
}).success(function(data, status, headers, config){
console.log(data);
this.auth = true
//get data from data...
}).error(function(data,status,headers,config){
console.log("error getted");
console.log(data);
});
}

关于angularjs - CORS、AngujarJS 和 NodejsAPI 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34087088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com