简体   繁体   English

节点JS应用程序部署到Heroku时中断

[英]Node JS App Breaking When Deployed to Heroku

I've recently deployed my Node JS ecommerce app to Heroku. 我最近将Node JS电子商务应用程序部署到了Heroku。 The app works fine in development, but I'm getting an application error in production when I visit /cart. 该应用程序在开发中运行良好,但是当我访问/ cart时,在生产中出现了应用程序错误。 I think I've managed to narrow the issue down to my use of cookies - my createCart function does not seem to be creating the necessary cookie to store the cart token. 我认为我已经设法解决了使用cookie的问题-我的createCart函数似乎并未创建存储购物车令牌的必要cookie。 Does anyone know what's causing this/how to fix it? 有谁知道是什么原因导致此问题/如何解决? Thanks! 谢谢!

heroku logs shows me this error: Error: Unhandled "error" event. (null) heroku logs向我显示此错误: Error: Unhandled "error" event. (null) Error: Unhandled "error" event. (null)

cart.js: 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);
});

}
app.set('trust proxy', 1)

将此添加到我的app.js中可以解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM