在我的静态文件中:
<form action="/confirm-purchase" method="post">
<input type="text" id="name" class="form-control" required name="name">
<input type="text" id="address" class="form-control" required name="address">
<input type="submit" value="Send Order" class="btn btn-success">
</form>
单击发送订单时,代码应获取user
对象和cart
模型等数据,并将其放入模型order
中并保存他们到数据库。
但是,当我单击发送订单时,页面上出现错误,提示它无法读取未定义的属性'cart',并且该错误来自于我所在的行在cart
路由中声明了变量post
。 相同变量位于get
路径中,以某种方式没有引起问题。
我做错了什么?
在我的路线上:
// get
router.get("/confirm-purchase", (req, res, next) => {
if (!req.session.cart) {
return res.render("shop/confirm-purchase", {products: null});
}
var cart = new Cart(req.session.cart);
res.render("shop/confirm-purchase", {totalPrice: cart.totalPrice});
});
// post
router.post("/confirm-purchase", (res, req, next) => {
var cart = new Cart(req.session.cart);
if(!req.session.cart) {
return res.redirect("/shopping-cart");
}
var order = new Order({
user: req.user, //user is object placed by passport.js
cart: cart,
name: req.body.name,
address: req.body.address
});
order.save(() => {
req.flash("success", "Successfully bought product/s!");
req.session.cart = null;
res.redirect("/");
});
});
我的购物车型号:
module.exports = function Cart(oldCart) {
this.items = oldCart.items || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0;
this.add = function(item, id) {
var storedItem = this.items[id];
if (!storedItem) {
storedItem = this.items[id] = {item: item, qty: 0, price: 0};
}
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty++;
this.totalPrice += storedItem.item.price;
}
this.generateArray = function() {
var arr = [];
for (var id in this.items) {
arr.push(this.items[id]);
}
return arr;
}
};
我的订单模型:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var schema = new Schema({
user: {type: Schema.Types.ObjectId, ref: "User"},
cart: {type: Object, required: true},
address: {type: String, required: true},
name: {type: String, required: true}
});
module.exports = mongoose.model("orderSchema", schema);
答案 0 :(得分:0)
我终于解决了:
res
和req
路由中的get
和post
参数以不同的顺序编写。
我的旧代码:
// get
router.get("/confirm-purchase", (req, res, next) => {/*...*/}
// post
router.post("/confirm-purchase", (res, req, next) => {/*...*/}
应该是:
// get
router.get("/confirm-purchase", (req, res, next) => {/*...*/}
// post
router.post("/confirm-purchase", (req, res, next) => {/*...*/}