将 Node、Express 和 MongoDB 服务器部署到 heroku
Posted
技术标签:
【中文标题】将 Node、Express 和 MongoDB 服务器部署到 heroku【英文标题】:Deploy Node, Express, and MongoDB server to heroku 【发布时间】:2021-06-22 05:28:41 【问题描述】:我使用 Node、Express 和 MongoDB Atlas 创建了一个服务器。这是这段代码:
server.js:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
// model
let Cards = require('./models/cards.model');
// App config
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
// DB config
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true );
const connection = mongoose.connection;
connection.once('open', () =>
console.log("MongoDB database connection has been established successfully.");
)
// API Endpoints
// POST parameter
app.post('/tinder/cards', (req, res) =>
const card = req.body;
Cards.create(card, (err, data) =>
if(err)
return res.status(500).send(err)
else
return res.status(200).send(data)
)
)
// GET parameter
app.get('/', (req, res) =>
return res.status(200).send("Welcome to Tinder Clone Backend with NodeJS, ExpressJS, and MongoDB!!!")
)
app.get('/tinder/cards', (req, res) =>
Cards.find((err, data) =>
if(err)
return res.status(500).send(err);
else
return res.status(200).send(data)
)
);
// Listener
app.listen(port, () =>
console.log(`Server is running on port $port`)
);
package.json
"name": "tinder-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts":
"test": "echo \"Error: no test specified\" && exit 1"
,
"keywords": [],
"author": "",
"license": "ISC",
"dependencies":
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.12.2"
cards.model.js
// creating database schema using mongoose
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const cardsSchema = new Schema(
name: String,
imgUrl: String
);
const Cards = mongoose.model('Cards', cardsSchema);
module.exports = Cards;
它在本地工作,所有端点都从 mongodb atlas 发送和接收数据。 当我在终端中运行此命令以启动本地服务器时: $ nodemon 服务器
它显示了这个:
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Server is running on port 5000
MongoDB database connection has been established successfully.
这意味着我的本地服务器运行良好,当我在浏览器中检查并输入我的服务器链接即 http://localhost:5000/tinder/cards 时,它显示的数据是我以前发布过:
[
"_id": "605a53881dedb514dcc1c4f2",
"name": "Elon Musk",
"imgUrl": "https://s3.india.com/wp-content/uploads/2020/03/Elon-Musk-AP.jpg",
"__v": 0
,
"_id": "605a53881dedb514dcc1c4f3",
"name": "Shakira",
"imgUrl": "https://ichef.bbci.co.uk/news/976/cpsprodpb/738B/production/_116497592_gettyimages-971720370.jpg",
"__v": 0
,
"_id": "605a53881dedb514dcc1c4f4",
"name": "Jeff Bezos",
"imgUrl": "https://media.wired.com/photos/6019cab23453f789506008d0/master/pass/Sec_Bezos_1036084400.jpg",
"__v": 0
,
"_id": "605a53881dedb514dcc1c4f5",
"name": "Dua Lipa",
"imgUrl": "https://assets.vogue.com/photos/5f48136693122510d16f0352/4:3/w_1080,h_810,c_limit/118520052_586967341971321_6121798062289952442_n.jpg",
"__v": 0
,
"_id": "605a53881dedb514dcc1c4f6",
"name": "Pitbull",
"imgUrl": "https://vz.cnwimg.com/wp-content/uploads/2010/03/Pitbull.jpg",
"__v": 0
,
"_id": "605a53881dedb514dcc1c4f7",
"name": "Ellen",
"imgUrl": "https://www.geo.tv/assets/uploads/updates/2021-03-18/340307_5260100_updates.jpg",
"__v": 0
,
"_id": "605a53881dedb514dcc1c4f8",
"name": "Bill Gates",
"imgUrl": "https://www.incimages.com/uploaded_files/image/1920x1080/getty_1185999101_20001333200092800_443629.jpg",
"__v": 0
,
"_id": "605a53881dedb514dcc1c4f9",
"name": "Taylor Swift",
"imgUrl": "https://static.onecms.io/wp-content/uploads/sites/20/2020/12/02/taylor-swift1.jpg",
"__v": 0
,
"_id": "605a53881dedb514dcc1c4fa",
"name": "Engin Altan",
"imgUrl": "https://www.incpak.com/wp-content/uploads/2020/09/50094085_2224186024567959_693900883193935752_n.jpg",
"__v": 0
,
"_id": "605a53881dedb514dcc1c4fb",
"name": "Esra Bilgic",
"imgUrl": "https://i.dawn.com/large/2021/01/6007fbceb61de.png",
"__v": 0
]
但是当我将同一台服务器部署到 heroku 时,在我测试它时它显示一个空对象。
当我在终端中运行此命令时: $ heroku logs --tails
显示这个错误:
2021-03-25T11:08:08.715303+00:00 app[web.1]: (node:21) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: Could not connect to
any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted.
Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
2021-03-25T11:08:08.715323+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:839:32)
2021-03-25T11:08:08.715324+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:348:10
2021-03-25T11:08:08.715326+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
2021-03-25T11:08:08.715326+00:00 app[web.1]: at new Promise (<anonymous>)
2021-03-25T11:08:08.715327+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
2021-03-25T11:08:08.715328+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1152:10)
2021-03-25T11:08:08.715328+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:347:20)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:23:10)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1063:30)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
2021-03-25T11:08:08.715330+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:928:32)
2021-03-25T11:08:08.715330+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:769:14)
2021-03-25T11:08:08.715331+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
2021-03-25T11:08:08.715331+00:00 app[web.1]: at internal/main/run_main_module.js:17:47
2021-03-25T11:08:08.715332+00:00 app[web.1]: (Use `node --trace-warnings ...` to show where the warning was created)
2021-03-25T11:08:08.721117+00:00 app[web.1]: (node:21) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated
either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To term
inate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html
#cli_unhandled_rejections_mode). (rejection id: 1)
2021-03-25T11:08:08.721508+00:00 app[web.1]: (node:21) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the fut
ure, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
部署在 heroku 上的服务器显示的是空对象,而不是我发布的数据, 当我输入 heroku 服务器的 URL 时,即 https://tinder-clone-backend-mern.herokuapp.com/tinder/cards :
我怎样才能让这个服务器像本地服务器一样完美地工作?
【问题讨论】:
【参考方案1】:尝试在您的 Atlas 集群/网络访问中将 IPS 设置为可用于所有 IPS (0.0.0.0/0) 如果修复,请告诉我。
【讨论】:
我已经检查过了,它显示同样的错误。 您的根应用程序中有 Procfile 文件吗?而且你还必须在你的 package.json 中添加一个脚本 - 开始 - 启动应用程序的命令。你都拥有了吗? 我的根应用程序中既没有 Procfile 文件,也没有 package.json 中的启动命令 const uri = process.env.ATLAS_URI; process.env 属于 heroku,您不能以这种方式设置数据库选项。将它们以纯文本形式写入文件中。以上是关于将 Node、Express 和 MongoDB 服务器部署到 heroku的主要内容,如果未能解决你的问题,请参考以下文章
Node.JS、Express 和 MongoDB :: 多个集合
将图像文件从 React 前端上传到 Node/Express/Mongoose/MongoDB 后端(不工作)
错误状态:使用 Node.js (express)、Angular 和 MongoDB 的 PUT 请求返回 404
通过 Express / Node JS 将配置文件从 HTML 编辑到 MongoDB