当张贴到数据库时,I'我得到了一个“;可以't在它们被发送错误之后设置报头”;
When POSTing to the database, I'm getting a "Can't set headers after they are sent error"
在这个问题中,我发布了从开始到结束的完整销售数据流,因为我不知道错误在哪里。在我的应用程序中,我在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标头。
基本上:在将任何内容打印到屏幕上之前,只需确保您的标题已被发送,这就是错误的含义。
- 当张贴到数据库时,I'我得到了一个“;可以't在它们被发送错误之后设置报头”;
- 有没有一种方法可以在所有嵌套循环之后放置一个标签,以便在一步中将它们全部打断
- 可以使 jquery 点击事件在所有其他点击事件之后执行
- 可以't在动态附加CKEDITOR对象之后访问它
- 可以'在使用Javascript/AjaxMVC之后,不会返回到任何视图
- 在动态创建html元素之后,是否可以触发事件
- regex某个字符可以存在也可以不存在,但之后什么都没有
- 是否可以在更改事件之后立即检测到 onclick 事件
- 是否可以在特定的console.log()条目之后执行Javascript函数
- 在定义了构造函数之后,是否可以将实例属性添加到JavaScript原型中
- Node.js,错误344,可以't在设置标头之后设置标头
- 有没有我可以听的事件发生在表单提交之后,并且在表单通过HTML5验证之后
- 我可以在 Javascript 中的 onclick 中的“this”之后插入字符串吗?
- 搜索引擎优化在骨干应用程序中,以便谷歌可以在phantomjs之后索引主页
- 我可以阻止我的 HTML 页面加载,直到我的 Facebook 登录状态脚本运行之后
- JQuery 插件可以在 JQuery 方法链上调用,还是需要在选择器之后直接调用
- 是否可以在 javascript 中的 decleration 语句之后将初始值分配给 const 变量
- 节点保存错误“;可以't在它们被发送之后设置报头”;
- javascript可以在调用者之后定义被调用者,以及如何解析它
- 可以't在使用node js将动态字段值插入mysql DB时,在发送头之后设置头