【问题标题】:nodejs express how to send response back to browsernodejs表达如何将响应发送回浏览器
【发布时间】: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 你有什么错误吗?

标签: node.js mongodb express


【解决方案1】:

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

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)
            }
        }
    })
});

【讨论】:

  • 谢谢@Yamini。我在浏览器中收到消息,但在服务器端应用程序崩溃并显示消息“MongoError:E11000 重复密钥错误集合:myapp.users 索引:email_1 dup key”
  • find 和 insert 都是异步进程,因此根据您的 sn-p 一个进程的回调不会等待另一个进程的回调。
  • 您能否解释一下您的确切用例,以便我提供帮助。在我看来,您的 find 函数返回“用户已在 db 中找到”,并且您的插入函数仍然尝试在用户并行执行时插入用户
  • 谢谢@Yamini。但是这个解决方案给出了错误,“MongoError: E11000 duplicate key error collection: myapp.users index: email_1 dup key:”
  • @sand 你能告诉我 findOne 的响应是什么,如果找到用户的话,在我看来它没有进入 if(err) block 。如果我是对的,那么我们将不得不检查 else 块,例如 if(err) { send error to front end} else { if(user found condition ) send message to front end else do insert operation }
【解决方案2】:

因为node js 工作asynchrounously 你的insert 不会等待findOne 完成所以你得到duplicate error

需要insertfindOne回调函数中的数据

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' })

            })
        }
    });

}); 

【讨论】:

  • 谢谢@Sravan。但是这个解决方案给出了错误,“TypeError: Cannot read property 'sort' of undefined”和“TypeError: cb is not a function”错误。
  • 你把sort带到哪里了
  • 对不起@Sravan,我收到“MongoError:E11000 重复密钥错误集合:myapp.users index:email_1 dup key:”消息。和应用程序崩溃。
  • 也请findOne响应中的console.log(data)
  • 此解决方案给出错误,“process.nextTick(function() { throw err; }); TypeError: First argument must be a string or Buffer”。这是针对行“res.end({ data: 'user found already in db' })”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 2019-10-23
  • 2011-11-06
  • 2014-12-22
  • 2011-08-07
相关资源
最近更新 更多