【发布时间】:2018-05-27 00:09:53
【问题描述】:
我正在尝试使用 angularjs 和 express 在 nodejs 中创建一个登录应用程序。从 angularjs 我向服务器发送 $http post 请求,首先它应该检查数据是否已经存在于 MongoDB 中并将响应发送回客户端。
问题是,我无法使用标头信息配置响应。每次我都得到
错误:发送后无法设置标头。
或
MongoError: E11000 重复键错误集合
Here is my app.js code.
app.post('/signin',function (req,res) {
console.log('i recievied a get request in app.js = /signin');
console.log(req.body);
db.users.findOne({$or: [{username: req.body.username}, {email: req.body.email}]},function (err, data){
if ( err ) throw err;
if (err) { res.send(err); return; }
//res.json({ data: "Invalid Password" });
if ( err ) {console.log('user found already in db'); console.log(err)};
//res.json(data);
//console.log('user found already in db')
//res.redirect('/foo/bar');
res.end('user found already in db');
//res.send({ data: 'user found already in db' })
//res.setHeader('Content-Type', 'application/json');
//res.json({ a: 1 });
//res.writeHead(200, {'Content-Type': 'text/plain'});
//res.send("jai shree ram");
//res.end();
//return;
});
db['users'].insert({
username : req.body.username,
firstname : req.body.firstname,
lastname : req.body.lastname,
email : req.body.email,
password : req.body.password,
createdAt : new Date(),
role : "user",
approvedBy : req.body.approver.username,
status : "locked"
},function (err, data){
if ( err ) throw err;
//if ( err ) {console.log('user created in db'); console.log(err)};
//res.json(data);
//if (err) { res.send(err); return; }
//res.json({ data: "Password" });
res.end('user created in db');
//res.send({ data: 'user created in db' })
//res.setHeader('Content-Type', 'application/json');
//res.json({ a: 1 });
//res.end();
//return;
})
});
从浏览器中我把请求放在下面
$http({
url: '/signin',
method: "POST",
data: $scope.SignInForm
//headers: {'Content-Type': 'myapplication/json','charset' : 'utf-8'}
})
.then(function (res){
console.log(res.data)
},function (error){
console.log(error)
});
我尝试了很多东西,但都没有成功。
【问题讨论】:
-
你在浏览器上得到了什么?服务器是否抛出任何错误?
-
不@Theo,我没有在浏览器中遇到错误。我将根据响应在浏览器中弹出响应消息。
-
你能在chrome的网络工具上打印什么响应码和正文吗?以及服务器日志?这是我们可以帮助你交配的唯一方法
-
为什么收到很多错误回复,发
res.end(err); -
@sand 你有什么错误吗?