我最近将我的Node JS电子商务应用程序部署到了Heroku。该应用程序在开发中运行良好,但是当我访问/购物车时,我在生产中遇到了应用程序错误。我想我已经设法将问题缩小到我对cookie的使用 - 我的createCart函数似乎没有创建存储购物车令牌的必要cookie。有谁知道造成这个/如何解决它的原因是什么?谢谢!
heroku logs
向我显示了此错误:Error: Unhandled "error" event. (null)
cart.js:
module.exports = function(app){
// Dependencies and imported functions
const cookie = require('cookie');
const path = require('path');
const appDir = path.dirname(require.main.filename);
const cartMod = require("../modules/cart");
const cartCount = cartMod.itemCount;
const crypto = require("crypto");
// DB
const Cart = require('../models/carts');
const CartItem = require('../models/cart_items');
const Discount = require('../models/discounts');
const Product = require('../models/products');
const createCart = (req, res, next) => {
var token = crypto.randomBytes(20).toString("hex");
Cart.create({token: token, discount: null}, function(err, cart) {
if (err || !cart) throw err;
console.log(token);
res.setHeader('Set-Cookie', cookie.serialize("cart_token", token, {
path: "/",
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
return next();
});
};
const checkCart = (req, res, next) => {
var token = req.cookies["cart_token"];
if (!token) {
createCart(res, res, next);
} else {
Cart.find({token: token}, function(err, cart) {
if (err || !cart) createCart(res, res, next);
return next();
});
}
};
const cartIndex = (req, res, cartCount) => {
var token = req.cookies["cart_token"];
console.log(token)
Cart.findOne({token: token}, function(err, cart) {
if (err || !cart) throw err;
if (cart.discount) {
Discount.findById(cart.discount, function(err, discount) {
if (err || !discount) throw err;
console.log(discount)
displayCartItems(res, cart._id, discount.percent, cartCount);
});
} else {
displayCartItems(res, cart._id, 0, cartCount);
}
});
};
app.get('/cart', checkCart, function (req, res, next) {
cartCount(req, res, cartIndex);
});
}
答案 0 :(得分:0)
app.set('trust proxy', 1)
将此添加到我的app.js中可以解决此问题。