node.js - 模型在发布路由中返回未定义的属性但没有获取路由
问题描述
在我的静态文件中:
<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
在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);
解决方案
终于搞定了:and路由中的res
andreq
参数是按不同的顺序写的。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) => {/*...*/}
推荐阅读
- php - 是否可以通过设置时间戳重用 datetime 对象?
- javascript - 在 node-ftp 模块中捕获未捕获的异常错误
- oracle - 按下按钮时触发器引发未处理的异常 ora-01401
- ssh - SSH 到 ECS Fargate 任务中的 docker 容器
- json - 我正在尝试将 json 对象转换为 csv 对象
- mysql - 如何在postgres中将两个select语句作为两列
- javascript - 在 Angular 6 中保留 form.reset() 上的选择字段占位符
- c - 使用 c 中的 dll 在 Labview 中处理图像
- php - 注入控制器中的函数有多少模型名称[基于问题]?
- unit-testing - Azure Dev Ops 构建管道 xunit 嵌套失败(.net 核心)