首页 > 解决方案 > 模型在发布路由中返回未定义的属性但没有获取路由

问题描述

在我的静态文件中:

    <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并保存到数据库中。

但是,当我单击发送订单时,页面上会出现一个错误,说它无法读取未定义的属性“购物车”,并且该错误来自我cartpost路由中声明变量的行。相同的变量在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);

标签: node.jspostmodelschemaexpress-session

解决方案


终于搞定了:and路由中的resandreq参数是按不同的顺序写的。getpost

我的旧代码:

// 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) => {/*...*/}

推荐阅读