使用ajax post方法控制台记录数据 [英] console logging data with ajax post method

查看:145
本文介绍了使用ajax post方法控制台记录数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图通过jquery发出发布请求,然后在请求的回调函数中console.log数据对象. 客户端:

So I am trying to make a post request via jquery and then console.log the data object in the callback function of the request. client-side:

var save = $('<button/>',{
        class: 'btn btn-link',
        id: url,
        type: 'submit',
        value: 'Submit',
        text: 'save for later?',
        click: function(event){
            var reqData = { article : this.id};
            $.post('/profile', reqData, function(data){
                console.log(data);
            })
        }

服务器端:

router.post('/profile', function(req, res) {
console.log(req.body);
// User.find();
console.log(req.user._id);
var article = new Article({article: req.body.article});


article.save(function(error, doc) {
        if (error) {
            res.send(error);
        } else {

            var id = doc._id;
            User.findOneAndUpdate({
                _id: req.user._id
            }, {$push :{
                article: id
            }}).exec(function(err, doc) {
                if (err) {
                    res.send(err);
                } else {
                   res.send(doc);
                }
            })
            res.send(doc);
        }
})

我不断收到错误消息发送后无法设置标题",如果我注释掉res.send(doc);在.exec承诺中,那么数据将为console.log,但是页面将​​快速刷新和擦除它.

I keep getting the error message 'can't set headers after they are sent', and if I comment out the res.send(doc); within the .exec promise, then the data will console.log, but the page will quickly refresh and erase it.

推荐答案

错误'can't set headers after they are sent'表示您试图多次响应.最终的res.send最初将被发送,然后在评估exec回调的if/else之后,将尝试第二个res.send.

The error 'can't set headers after they are sent' means that you are trying to respond multiple times. The final res.send is being sent initially, and then once the exec callback's if/else is evaluated, a second res.send is attempted.

这篇关于使用ajax post方法控制台记录数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆