简体   繁体   English

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

[英]Deploy Node, Express, and MongoDB server to heroku

I created a server using Node, Express, and MongoDB Atlas.我使用 Node、Express 和 MongoDB Atlas 创建了一个服务器。 Here is the code of this:这是这个的代码:

server.js: 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 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卡片.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;

It is working locally and all endpoints sending and receiving data from mongodb atlas.它在本地工作,所有端点都从 mongodb 地图集发送和接收数据。 when I run this command in terminal to start the local server: $ nodemon server当我在终端中运行此命令以启动本地服务器时: $ nodemon server

it is showing this:它显示了这一点:

[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.

This means that my local server is running well and when I check in my browser and type in my server link ie http://localhost:5000/tinder/cards , it showing data that I have posted previously:这意味着我的本地服务器运行良好,当我检查我的浏览器并输入我的服务器链接即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
}
]

But when I deployed the same server to heroku, it is showing an empty object when I testing it.但是,当我将同一台服务器部署到 heroku 时,它在测试时显示为空的 object。

When I run this command into my terminal: $ heroku logs --tails当我在终端中运行此命令时: $ heroku logs --tails

It is showing this error:它显示此错误:

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.

my server that is deployed on heroku is showing empty object instead of that data that I have posted, when I type URL of heroku server ie https://tinder-clone-backend-mern.herokuapp.com/tinder/cards : my server that is deployed on heroku is showing empty object instead of that data that I have posted, when I type URL of heroku server ie https://tinder-clone-backend-mern.herokuapp.com/tinder/cards :

{}

How can I make this server work perfectly as the local server does?如何使该服务器像本地服务器一样完美运行?

Try setting IPS, in your Atlas cluster/Network Access, to be available for all IPS (0.0.0.0/0) Let me know if it fixes.尝试在 Atlas 集群/网络访问中将 IPS 设置为可用于所有 IPS (0.0.0.0/0) 如果它修复,请告诉我。

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

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