【问题标题】:When POSTing to the database, I'm getting a "Can't set headers after they are sent error"发布到数据库时,我收到“发送错误后无法设置标题”
【发布时间】:2016-09-08 14:39:47
【问题描述】:

在这个问题中,我发布了从头到尾进行销售的完整数据流,因为我不知道错误在哪里。在我的应用程序中,我在 Checkout 组件中调用了一个名为 handlePay() 的函数,该函数又调用了一个名为 makeSale() 的动作创建者。 makeSale() 然后向 router.js 中的服务器发出 POST 请求,该服务器将使用 mongoose 在数据库中处理此销售。来自控制台的错误读取

"/Users/marcushurney/Desktop/P.O.S./node_modules/mongodb/lib/utils.js:98 process.nextTick(function() { throw err; }); ^

错误:发送后无法设置标头。"

我不确定这个错误是否存在于我与 router.js 中的数据库或前端其他地方的数据库通信的代码中。前端的组件称为 Checkout.jsx,处理销售的函数是 handlePay(),其关联的操作创建者是 makeSale()。

Checkout.jsx

handlePay: function() {

        var props = {
            user_id: this.props.activeUser._id, //This sale will belong to the user that is logged in (global state)
            items: [], //All the items in the cart will be added to the sale below (global state)
            total: this.props.cartTotal //Total price of the sale is drawn from the global state
        }


        this.props.cart.map((product) => {
            var item = {};
            item.name = product.name;
            item.product_id = product._id;
            item.cartQuantity = product.cartQuantity;
            item.priceValue = product.price;
            props.items.push(item);
        });

        var jsonProps = JSON.stringify(props); //converts properties into json before sending them to the server

        this.props.makeSale(jsonProps); 
    }

actions/index.js

export function makeSale(props) {

    var config = {headers: {'authorization' : localStorage.getItem('token')}};

    var request = axios.post('/makeSale', props, config); //This will store the sale in the database and also return it

    return {
        type: MAKE_SALE,
        payload: request //Sends sale along to be used in sale_reducer.js
    };

}

router.js

    //Adds a new sale to the database
    //Getting error "can't set headers after they are sent"

    app.post('/makeSale', function(req, res, next){

        var sale = new Sale();
        sale.owner = req.body.user_id;
        sale.total = req.body.total;

        req.body.items.map((item)=> {

            //pushs an item from the request object into the items array           contained in the sale document

            sale.items.push({
                item: item.product_id,
                itemName: item.name,
                cartQuantity: parseInt(item.cartQuantity), //adds cartQuantity to sale
                price: parseFloat(item.priceValue)
            });


            Product.findById(item.product_id)
            .then((product) => {

                //finds the item to be sold in the database and updates its quantity field based on the quantity being sold

                product.quantity -= item.cartQuantity; 

                //resets the product's cartQuantity to 1

                product.cartQuantity = 1;

                product.save(function(err) {
                    if (err) { 
                        return next(err); 
                    } else {
                        return next();
                        // return res.status(200).json(product);
                    }
                });
            }, (error) => {
              return next(error);
            });
        });

        //gives the sale a date field equal to current date

        sale.date = new Date();

        //saves and returns the sale

        sale.save(function(err) {
            if (err) { return next(err); }
            return res.status(200).json(sale); //Returns the sale so that it can be used in the sale_reducer.js
        });

    });

这里是 mongoose 的销售模型 --> sale.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var SalesSchema = new Schema({
    owner: { type: Schema.Types.ObjectId, ref: 'User'},
    total: { type: Number, default: 0},
    items: [{
        item: { type: Schema.Types.ObjectId, ref: 'Product'},
        itemName: { type: String, default: "no name provided"},
        cartQuantity: { type: Number, default: 1 },
        price: { type: Number, default: 0 }
    }],
    date: Date
});

module.exports = mongoose.model('Sale', SalesSchema);

【问题讨论】:

  • 这个社区不存在,因此人们可以在没有任何上下文的情况下发布巨大的代码墙,并期望其他人为他们解决问题。
  • 我不确定错误出在哪里,所以我发布了与数据流相关的所有代码,以便从头到尾进行销售。另外,我注意到大多数人总是要求我提供更多代码。您如何建议我将来更好地使用堆栈溢出?
  • 这是一个很好的观察,人们经常提出问题并且几乎不提供代码。很高兴您发布了工作流程中涉及的代码!这比平均水平有了很大的进步。有几种方法可以改进这篇文章,特别是为错误本身提供更多上下文(例如控制台输出)并提出更具体的问题。尽管您似乎已经在这里解决了您的问题并接受了答案,但请考虑使用更多上下文更新您的问题,以便后代可以更轻松地解决他们的问题。
  • 我继续为问题添加了更多上下文,并从控制台显示了错误。感谢您的帮助。
  • 谢谢!我将我的反对票改为赞成票。感谢您接受反馈并改进您的问题!

标签: javascript node.js reactjs mongoose react-redux


【解决方案1】:

Product.findById 是异步的,最终会多次调用next(),这将(很可能)导致尝试多次发送响应,从而导致您看到的错误。

通常(或总是,可能),您只想对每个中间件调用一次next()

试试这个:

"use strict";

app.post('/makeSale', function(req, res, next){

    var sale = new Sale();
    sale.owner = req.body.user_id;
    sale.total = req.body.total;

    return Promise.all(req.body.items.map((item) => {

        // pushs an item from the request object into the items array contained in the sale document
        sale.items.push({
            item: item.product_id,
            itemName: item.name,
            cartQuantity: parseInt(item.cartQuantity, 10), // adds cartQuantity to sale
            price: parseFloat(item.priceValue)
        });

        return Product.findById(item.product_id).then((product) => {

            //finds the item to be sold in the database and updates its quantity field based on the quantity being sold

            product.quantity -= item.cartQuantity; 

            //resets the product's cartQuantity to 1
            product.cartQuantity = 1;
            return product.save();
        });
    }))
    .then(() => {
        //gives the sale a date field equal to current date
        sale.date = new Date();

        //saves and returns the sale
        return sale.save();
    })
    .then(() => {
        return res.status(200).json(sale);
    })
    .catch(next);
});

【讨论】:

  • dvlsg,为什么要为 Product.findById 添加返回值?另外, use strict 在这里有什么作用?这段代码确实解决了问题,但我只是想了解更多。
  • 我返回Product.findById,因为它返回一个Promise,我们要做的是将req.body.items映射到Promises的数组,以便Promise.all()处理。关于Promise.all()的补充阅读。
  • 还要注意这里的代码是异步执行的并行,而不是顺序执行。这可能会给您带来麻烦,具体取决于您的数据。例如,如果您允许在 req.body.items 中使用相同的 product_id 的多个单独的对象,那么这些数量扣除可能会相互影响,您最终可能会得到错误的数量。我假设您不允许在多个项目中使用相同的 product_id,因为您使用的是数量。
【解决方案2】:

在您的路线中,您为每个保存的产品调用 next()。你打电话给res.status(200).json(sale)

调用 next() 告诉 Express 你的路由处理程序对处理请求不感兴趣,因此 Express 会将其委托给下一个匹配的处理程序(如果没有,则为通用 Not Found 处理程序)语气)。您随后无法再次致电next(),或自己回复回复,因为您已经告诉 Express 您不感兴趣。

您应该重写req.body.items.map(...),使其根本不调用next()

一种解决方案是使用async.map()。然后,您将在最终回调中调用 next(error)(如果有) res.json()

【讨论】:

    【解决方案3】:

    我很少将 JS 用于后端,但这通常意味着您在发送/发送 HTTP 正文之后尝试设置 HTTP 标头。

    基本上:只要确保在将任何内容打印到屏幕之前发送标题就是该错误的含义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 2021-03-15
      • 2015-11-13
      • 2015-03-07
      相关资源
      最近更新 更多