在POST到数据库时,我发现了一个"在发送错误之后无法设置标头错误"

时间:2016-05-12 16:17:03

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

在这个问题中,我发布了从头到尾进行销售的完整数据流,因为我不知道错误在哪里。在我的应用程序中,我在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

    byte 3         2        1        0
    don't care    'c'      'c'      'a'
  - don't care    'c'      'b'      'a'
    -----------------------------------
  = don't care     0        1        0
  &    0          0xFF     0xFF     0xFF
    -----------------------------------
  =    0           0        1        0   --> 256

操作/ index.js

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

router.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
    };

}

以下是猫鼬的销售模式 - > sale.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
        });

    });

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

在您的路线中,您为每个已保存的产品致电next()。您呼叫res.status(200).json(sale)

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

您应该重写req.body.items.map(...),以便它根本不会调用next()

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

答案 2 :(得分:0)

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

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