我的Node.js web应用程序,由Express, Mongoose和EJS构建,在Heroku上托管后不能工作。该应用程序连接到MongoDB Atlas数据库,并具有创建、读取、更新和删除产品的路由。该应用程序在本地主机上运行良好,但在部署到Heroku后,它无法连接到数据库,路由也不能像预期的那样工作。我无法找到问题的根本原因,需要帮助排除故障。
const { urlencoded } = require("body-parser")
const express = require("express")
const mongoose = require('mongoose')
const app = express()
const Product = require('./models/product')
const methodOverride = require('method-override')
mongoose.connect("mongodb+srv://user:pass123@cluster0.avm9sgy.mongodb.net/?retryWrites=true&w=majority", { useNewUrlParser: true }
).then(() => console.log("Database Connection succesful")).catch(() => console.log("error"))
app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: true }))
app.use(methodOverride('_method'))
app.get('/', async (req, res) => {
res.send('Hello')
})
app.get('/products', async (req, res) => {
const products = await Product.find({})
res.render('products/index', { products })
})
app.get('/products/new', async (req, res) => {
res.render('products/new')
})
app.post('/products', async (req, res) => {
const newProduct = new Product(req.body)
await newProduct.save()
console.log(newProduct)
res.redirect(`products/${newProduct._id}`)
})
app.get('/products/:id', async (req, res) => {
const { id } = req.params
const product = await Product.findById(id)
res.render('products/details', { product })
})
app.get('/products/:id/edit', async (req, res) => {
const { id } = req.params
const product = await Product.findById(id)
res.render('products/edit', { product })
})
app.put('/products/:id', async (req, res) => {
const { id } = req.params
const product = await Product.findByIdAndUpdate(id, req.body, { runValidators: true, new: true })
res.redirect(`/products/${product._id}`)
})
app.delete('/products/:id', async (req, res) => {
const { id } = req.params
const deletedProduct = await Product.findByIdAndDelete(id)
res.redirect(`/products/`)
})
app.listen(3000)
当与Heroku(开发人员最流行的PaaS解决方案之一)配对时,您将能够立即构建和部署完全托管的云应用程序。最好的部分是什么?MongoDB Atlas可以轻松地与Heroku应用程序集成。您所需要做的就是将Atlas集群的连接字符串设置为Heroku配置变量. 这就是它的全部内容!
按照这里的步骤操作