将 Node、Express 和 MongoDB 服务器部署到 heroku

时间:2021-03-25 12:02:18

标签: node.js mongodb express heroku mongoose

我使用 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 日志 --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 个答案:

答案 0 :(得分:0)

尝试在您的 Atlas 集群/网络访问中设置 IPS,使其对所有 IPS (0.0.0.0/0) 可用。如果它修复,请告诉我。