当张贴到数据库时,I'我得到了一个“;可以't在它们被发送错误之后设置报头”;

When POSTing to the database, I'm getting a "Can't set headers after they are sent error"

本文关键字:可以 之后 设置 错误 报头 数据库 张贴 一个      更新时间:2023-09-26

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

"/Users/marcushurney/Desktop/p.O.S/nod_module/mongodb/lib/utils.js:98process.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
        });
    });

这是猫鼬-->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);

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

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

调用next()会告诉Express您的路由处理程序对处理请求不感兴趣,因此Express会将其委托给下一个匹配的处理程序(如果没有,则委托一个通用的NotFound处理程序)。你不能再打next(),也不能自己回复,因为你已经告诉Express你不感兴趣了。

您应该重写req.body.items.map(...),这样它就不会调用next()

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

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

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

相关文章: