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

use*_*sam 1 mongodb node.js express

我正在尝试使用 angularjs 和 express 在 nodejs 中制作登录应用程序。从 angularjs 我发送 $http post 请求到 server ,首先它应该检查数据是否已经存在于 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;
    })

}); 
Run Code Online (Sandbox Code Playgroud)

从浏览器中,我将请求置于下方

$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)
            });
Run Code Online (Sandbox Code Playgroud)

我尝试了很多东西,但都没有成功。

Yam*_*bra 5

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

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

其次,您的插入和查找并行运行。只有在数据库中找不到用户时,插入才有效

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)
            }
        }
    })
});
Run Code Online (Sandbox Code Playgroud)