nodejs表示如何将响应发送回浏览器

时间:2018-05-26 13:02:01

标签: node.js mongodb express

我正在尝试使用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)
            });

我试了很多东西,但没能成功。

2 个答案:

答案 0 :(得分:3)

设置标头和发送数据的顺序错误。首先设置标题然后将响应发送到前端。

res.setHeader('Content-Type', 'application/json');
res.send({ data: 'user created in db' })

其次,您的插入和查找是并行运行的。只有在db

中找不到用户时才能使用插入
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) { 
            //Error Case (send to front end)
            res.send( error) 
        } else {
            if(data == null) {//Condition to check whether data exists or not
                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;   
                    res.setHeader('Content-Type', 'application/json');
                    res.send({ data: 'user created in db' })
                });
            } else {
                 res.send(data)
            }
        }
    })
});

答案 1 :(得分:0)

由于node js有效asynchrounously,您的insert不会等到findOne完成,因此您将获得duplicate error

insert

回调函数中需要findOne个数据
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 (data) {
            res.setHeader('Content-Type', 'application/json');
            res.end({ data: 'user found already in db' })
        }
        else {
            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) {
                    res.setHeader('Content-Type', 'application/json');
                    res.end({ data: err })
                }
                res.setHeader('Content-Type', 'application/json');
                res.send({ data: 'user created in db' })

            })
        }
    });

});