gpt4 book ai didi

javascript - 当发布到数据库时,我收到 "Can' t set headers after they are sent error”

转载 作者:行者123 更新时间:2023-11-30 11:58:49 25 4
gpt4 key购买 nike

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

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

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

我不确定我的代码中是否存在此错误,该代码与 router.js 中的数据库或前端的其他地方进行通信。前端组件称为 Checkout.jsx,处理销售的函数是 handlePay(),其关联的 Action 创建器是 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);

最佳答案

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

关于javascript - 当发布到数据库时,我收到 "Can' t set headers after they are sent error”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37192388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com