mongodb atlas_如何使用MongoDB Atlas將MERN應用程序部署到Heroku

mongodb atlas

簡介 (Introduction to MERN)

In this article, we'll be building and deploying an application built with the MERN stack to Heroku.

在本文中,我們將構建和部署使用MERN堆棧構建的應用程序到Heroku。

MERN, which stands for MongoDB, Express, React, and Node.js, is a popular tech stack used in building web applications. It involves frontend work (with React), backend work (with Express and NodeJS) and a database (with MongoDB).

MERN代表MongoDB,Express,React和Node.js,是用于構建Web應用程序的流行技術堆棧。 它涉及前端工作(使用React),后端工作(使用Express和NodeJS)和數據庫(使用MongoDB)。

Heroku, on the other hand, is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.

另一方面, Heroku是一個平臺即服務(PaaS),使開發人員可以完全在云中構建,運行和操作應用程序。

For the database, we'll be using MongoDB Atlas, which is a global cloud database service for modern applications. This is more secure than the MongoDB installed locally on our server and it also gives us room for more resources on our servers.

對于數據庫,我們將使用MongoDB Atlas,這是針對現代應用程序的全球云數據庫服務。 這比在服務器上本地安裝的MongoDB安全得多,并且還為我們的服務器上的更多資源提供了空間。

For the frontend we'll build a simple React app which makes POST requests to an API to add a user, and can also make GET requests to get all users.

對于前端,我們將構建一個簡單的React應用程序,該應用程序向API發送POST請求以添加用戶,還可以進行GET請求以獲取所有用戶。

You can skip to any step with the table of contents listed below.

您可以跳到下面列出的目錄中的任何步驟。

目錄 (Table of contents)

  • Introduction to MERN

    簡介

  • Let's Start Building

    讓我們開始建設

  • Building the React App

    構建React應用

  • Creating the Backend

    創建后端

  • Connect the MongoDB Atlas Database

    連接MongoDB Atlas數據庫

  • Calling APIs on the Frontend

    在前端調用API

  • Deploying to Heroku

    部署到Heroku

  • Create a Heroku app

    創建一個Heroku應用

  • Configure package.json

    配置package.json

  • Wrap up

    結語

讓我們開始建設 (Let's Start Building)

構建React應用 (Building the React App)

Note: Before we begin with our project, node must be installed on your computer. node also provides us with npm, which is used for installing packages.

注意:在開始我們的項目之前,必須在您的計算機上安裝nodenode還為我們提供了npm ,用于安裝軟件包。

安裝create-react-app (Install create-react-app)

create-react-app is used to create a starter React app.

create-react-app用于創建啟動程序React應用。

If you do not have create-react-app installed, type the following in the command line:

如果您尚未安裝create-react-app ,請在命令行中輸入以下內容:

npm i create-react-app -g

The -g flag installs the package globally.

-g標志在全局范圍內安裝軟件包。

創建項目目錄 (Create the project directory)

create-react-app my-project
cd my-project

The above creates a directory 'my-project', and installs dependencies which will be used in the React starter app. After it's finished installing, the second command changes to the project directory.

上面創建了一個目錄“ my-project”,并安裝了將在React starter應用程序中使用的依賴項。 安裝完成后,第二個命令將更改為項目目錄。

啟動應用程序并進行必要的編輯 (Start the app and make necessary edits)

npm start

The command above starts the React application, which gives you a URL where you preview the project. You can then make necessary edits like changing images or text.

上面的命令將啟動React應用程序,該應用程序為您提供一個URL,您可以在其中預覽項目。 然后,您可以進行必要的編輯,例如更改圖像或文本。

安裝axios (Install axios)

npm i axios --save

axios is a JavaScript library used to make HTTP requests easier. It'll be used to send requests from the frontend (React) to the APIs provided by the backend.

axios是一個JavaScript庫,用于axios HTTP請求。 它將用于將請求從前端(React)發送到后端提供的API。

創建后端 (Creating the Backend)

The backend manages the APIs, handles requests, and also connects to the database.

后端管理API,處理請求并連接到數據庫。

安裝后端軟件包 (Install the backend packages)

npm i express cors mongoose body-parser --save
  1. express: "Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web applications" - Express Documentation

    express :“ Express是一個最小且靈活的Node.js Web應用程序框架,為Web應用程序提供了一組強大的功能”-Express 文檔

  2. cors: "CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options" - cors Documentation

    cors :“ CORS是一個node.js軟件包,用于提供可用于通過各種選項啟用CORS的Connect / Express中間件” -cors文檔

  3. mongoose: "Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks" - Mongoose Documentation

    mongoose :“ Mongoose是一個旨在在異步環境中工作的MongoDB對象建模工具。Mongoose同時支持promise和回調。”- Mongoose文檔

  4. body-parser: "Node.js body parsing middleware." - body-parser Documentation

    body-parser :“ Node.js主體解析中間件”。 - 人體分析器文檔

創建后端文件夾 (Create the backend folder)

mkdir backend
cd backend

配置后端 (Configure the backend)

創建一個入口點server.js (Create an entry point server.js)

First, create a server.js file, which will be the entry point to the backend.

首先,創建一個server.js文件,它將是后端的入口。

touch server.js

In server.js, type the following:

server.js ,鍵入以下內容:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path')
const app = express();
require('./database');
-----
app.use(bodyParser.json());
app.use(cors());
-----
// API
const users = require('/api/users');
app.use('/api/users', users);
-----
app.use(express.static(path.join(__dirname, '../build')))
app.get('*', (req, res) => {res.sendFile(path.join(__dirname, '../build'))
})
-----
const port = process.env.PORT || 5000;
app.listen(port, () => {console.log(`Server started on port ${port}`);
});

express.static delivers static files which are the ones built when npm run build is run on a React project. Remember, the built file is in the build folder.

express.static提供靜態文件,這些文件是在React項目上運行npm run build時生成的。 請記住,生成的文件位于build文件夾中。

From our configuration, any request sent to /api/users will be sent to users API which we're about to configure.

從我們的配置中,任何發送到/api/users請求都將發送到我們將要配置的users API。

配置users API (Configure the users API)
mkdir api
touch api/users.js

In api/users.js, add the following:

api/users.js ,添加以下內容:

const express = require('express');
const router = express.Router()
-----
const User = require('../models/User');
-----
router.get('/', (req, res) => {User.find().then(users => res.json(users)).catch(err => console.log(err))
})
-----
router.post('/', (req, res) => {const { name, email } = req.body;const newUser = new User({name: name, email: email})newUser.save().then(() => res.json({message: "Created account successfully"})).catch(err => res.status(400).json({"error": err,"message": "Error creating account"}))
})
module.exports = router

In the code above, we create a GET and POST request handler which fetches all users and posts users. Fetching and adding a user to the database is aided by the User model we'll create.

在上面的代碼中,我們創建了GET和POST請求處理程序,該處理程序將提取所有用戶并發布用戶。 我們將創建的User模型幫助將User提取并添加到數據庫中。

創建User模型 (Create User model)
mkdir models
touch models/user.js

In models/user.js, add the following:

models/user.js ,添加以下內容:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
-----
const userSchema = new Schema({name: {type: String,required: true},email: {type: String,required: true}
})
module.exports = mongoose.model("User", userSchema, "users")

In the code above, a schema is created for the user which contains the fields of the user. At the end of the file, the model ("User") is exported with the schema and the collection ("users").

在上面的代碼中,為用戶創建了一個包含用戶字段的架構。 在文件末尾,模型(“用戶”)與模式和集合(“用戶”)一起導出。

連接MongoDB Atlas數據庫 (Connect the MongoDB Atlas Database)

According to the docs, "MongoDB Atlas is the global cloud database service for modern applications."

根據文檔 ,“ MongoDB Atlas是針對現代應用程序的全球云數據庫服務。”

First we need to register on Mongo cloud. Go through this documentation to create an Atlas account and create your cluster.

首先,我們需要在Mongo云上注冊。 瀏覽本文檔以創建Atlas帳戶并創建集群。

One thing worth noting is whitelisting your connection IP address. If you ignore this step, you won't have access to the cluster, so pay attention to that step.

值得注意的一件事是將您的連接IP地址列入白名單 。 如果您忽略此步驟,則您將無權訪問群集,因此請注意該步驟。

The cluster is a small server which will manage our collections (similar to tables in SQL databases). To connect your backend to the cluster, create a file database.js, which as you can see is required in server.js. Then enter the following:

集群是一臺小型服務器,將管理我們的集合(類似于SQL數據庫中的表)。 要將后端連接到集群,請創建一個文件database.js ,如您所見,該文件在server.js是必需的。 然后輸入以下內容:

const mongoose = require('mongoose');
const connection = "mongodb+srv://username:<password>@<cluster>/<database>?retryWrites=true&w=majority";
mongoose.connect(connection,{ useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false}).then(() => console.log("Database Connected Successfully")).catch(err => console.log(err));

In the connection variable, enter your username (for MongoDB cloud), your password (cluster password), your cluster (address for your cluster) and the database (name of your database). All these can be easily discovered if you followed the documentation.

connection變量中,輸入username (對于MongoDB云), password (集群密碼), cluster ( cluster地址)和database ( database名稱)。 如果遵循文檔,所有這些內容都可以輕松發現。

在前端調用API (Calling APIs on the Frontend)

All APIs will be available on localhost:5000 locally, just as we set up in server.js. When deployed to Heroku, the server will use the port provided by the server (process.env.PORT).

就像我們在server.js設置的一樣,所有API都將在localhost:5000上可用。 部署到Heroku后,服務器將使用服務器提供的端口( process.env.PORT )。

To make things easier, React allows us to specify a proxy which requests will be sent to.

為了使事情變得更容易,React允許我們指定一個將請求發送到的代理。

Open package.json and just before the last curly brace, add the following:

打開package.json并在最后一個花括號之前添加以下內容:

"proxy": "http://localhost:5000"

This way we can directly send requests to api/users. And when our site is deployed and built, the default port of our application will be used with the same API.

這樣,我們可以直接將請求發送到api/users 。 在部署和構建我們的站點時,我們的應用程序的默認端口將與相同的API一起使用。

Open App.js for React and add the following:

打開App.js for React并添加以下內容:

import React, {useState, useEffect} from 'react'
import axios from 'axios';
-----
const App = function () {const [users, setUsers] = useState(null);const [username, setUsername] = useState("");const [email, setEmail] = useState("");useEffect(() => {axios.get("/api/users").then((users) => setUsers(users)).catch((err) => console.log(err));}, []);function submitForm() {if (username === "") {alert("Please fill the username field");return;}if (email === "") {alert("Please fill the email field");return;}axios.post("/api/users", {username: username,email: email,}).then(function () {alert("Account created successfully");window.location.reload();}).catch(function () {alert("Could not creat account. Please try again");});}return (<><h1>My Project</h1>{users === null ? (<p>Loading...</p>) : users.length === 0 ? (<p>No user available</p>) : (<><h2>Available Users</h2><ol>{users.map((user, index) => (<li key={index}>Name: {user.name} - Email: {user.email}</li>))}</ol></>)}<form onSubmit={submitForm}><inputonChange={(e) => setUsername(e.target.value)}type="text"placeholder="Enter your username"/><inputonChange={(e) => setEmail(e.target.value)}type="text"placeholder="Enter your email address"/><input type="submit" /></form></>);
};
export default App

The useState and useEffect hooks are used to handle state and sideEffects. What is basically happening is that the first state of users is null and 'Loading...' is showed in the browser.

useStateuseEffect掛鉤用于處理state和sideEffects 。 基本上發生的是用戶的第一狀態為null并且在瀏覽器中顯示“正在加載...”。

In useEffect, [] is used to specify that at the componentDidMount stage (when the component is mounted), make an Axios request to the API which is running on localhost:5000. If it gets the result and there is no user, 'No user available' is displayed. Otherwise a numbered list of the users is displayed.

useEffect[]用于指定在componentDidMount階段(安裝組件時),向在localhost:5000上運行的API發出Axios請求。 如果得到結果并且沒有用戶,則顯示“無用戶可用”。 否則,將顯示編號的用戶列表。

If you want to learn more about useState and useEffect, check out this article - What the heck is React Hooks?

如果您想了解更多有關useStateuseEffect ,請查看本文useEffect Hooks到底是什么?

With the form available, a POST request can be made to post a new user. The state of the inputs are controlled and sent to the API at localhost:5000 on submission. Afterwards, the page is refreshed and the new user is displayed.

使用可用的表格,可以發出POST請求以發布新用戶。 輸入的狀態受到控制,并在提交時通過localhost:5000發送到API。 之后,刷新頁面并顯示新用戶。

部署到Heroku (Deploying to Heroku)

To deploy your application to Heroku, you must have a Heroku account.

要將應用程序部署到Heroku,您必須具有一個Heroku帳戶。

Go to their page to create an account. Then go through their documention on how to create a Heroku app. Also check out the documentation on Heroku CLI.

轉到他們的頁面以創建一個帳戶。 然后閱讀他們有關如何創建Heroku應用程序的文檔 。 另請查看Heroku CLI上的文檔 。

創建一個Heroku應用 (Create a Heroku App)

First, login to Heroku:

首先,登錄Heroku:

heroku login

This will redirect you to a URL in the browser where you can log in. Once you're finished you can continue in the terminal.

這會將您重定向到瀏覽器中可以登錄的URL。完成后,您可以在終端中繼續。

In the same React project directory, run the following:

在同一React項目目錄中,運行以下命令:

heroku create

This will create a Heroku application and also give you the URL to access the application.

這將創建一個Heroku應用程序,并為您提供訪問該應用程序的URL。

配置package.json (Configure package.json)

Heroku uses your package.json file to know which scripts to run and which dependencies to install for your project to run successfully.

Heroku使用您的package.json文件來了解要運行的腳本以及要成功安裝的依賴項。

In your package.json file, add the following:

在您的package.json文件中,添加以下內容:

{..."scripts": {..."start": "node backend/server.js","heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install npm && run build"},..."engines": {"node": "10.16.0"}
}

Heroku runs a post build, which as you can see installs your dependencies and runs a build of your React project. Then it starts your project with the start script which basically starts your server. After that, your project should work fine.

Heroku運行一個后構建,如您所見,它將安裝您的依賴關系并運行您的React項目的構建。 然后,它使用start腳本來啟動您的項目,該腳本基本上會啟動您的服務器。 之后,您的項目應該可以正常運行。

engines specifies the versions of engines like node and npm to install.

engines指定要安裝的引擎(如nodenpm的版本。

推送到Heroku (Push to Heroku)

git push heroku master

This pushes your code to Heroku. Remember to include unnecessary files in .gitignore.

這會將您的代碼推送到Heroku。 請記住在.gitignore包括不必要的文件。

After few seconds your site will be ready. If there are any errors, you can check your terminal or go to your dashboard in the browser to view the build logs.

幾秒鐘后,您的網站將準備就緒。 如果有任何錯誤,您可以檢查終端或在瀏覽器中轉到儀表板以查看構建日志。

Now you can preview your site at the URL Heroku sent when you ran heroku create.

現在,您可以使用運行heroku create時發送的URL Heroku預覽站點。

That's all there is to it. Glad you read this far.

這里的所有都是它的。 很高興您閱讀了這么遠。

結語 (Wrap Up)

Of course there is more to MERN stack applications.

當然,MERN堆棧應用程序還有更多。

This article did not go as deep as authentications, login, sessions, and all that. It just covered how to deploy MERN stack applications to Heroku and work with MongoDB Atlas.

本文不像身份驗證,登錄,會話以及所有其他內容那么深入。 它僅介紹了如何將MERN堆棧應用程序部署到Heroku以及如何使用MongoDB Atlas。

You can find other articles like this on my blog - dillionmegida.com

您可以在我的博客-dillionmegida.com上找到其他類似的文章

Thanks for reading.

謝謝閱讀。

翻譯自: https://www.freecodecamp.org/news/deploying-a-mern-application-using-mongodb-atlas-to-heroku/

mongodb atlas

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390486.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390486.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390486.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

面試題 10.02. 變位詞組

編寫一種方法&#xff0c;對字符串數組進行排序&#xff0c;將所有變位詞組合在一起。變位詞是指字母相同&#xff0c;但排列不同的字符串。 注意&#xff1a;本題相對原題稍作修改 示例: 輸入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”], 輸出: [ [“ate”,…

智能合約設計模式

2019獨角獸企業重金招聘Python工程師標準>>> 設計模式是許多開發場景中的首選解決方案&#xff0c;本文將介紹五種經典的智能合約設計模式并給出以太坊solidity實現代碼&#xff1a;自毀合約、工廠合約、名稱注冊表、映射表迭代器和提款模式。 1、自毀合約 合約自毀…

如何使用1Password,Authy和Privacy.com外包您的在線安全性

Take some work off your plate while beefing up security with three changes you can make today.通過今天可以進行的三項更改來增強安全性&#xff0c;同時省下一些工作。 Unstable times are insecure times, and we’ve already got enough going on to deal with. When…

「CodePlus 2017 12 月賽」火鍋盛宴

n<100000種食物&#xff0c;給每個食物煮熟時間&#xff0c;有q<500000個操作&#xff1a;在某時刻插入某個食物&#xff1b;查詢熟食中編號最小的并刪除之&#xff1b;查詢是否有編號為id的食物&#xff0c;如果有查詢是否有編號為id的熟食&#xff0c;如果有熟食刪除之…

5815. 扣分后的最大得分

給你一個 m x n 的整數矩陣 points &#xff08;下標從 0 開始&#xff09;。一開始你的得分為 0 &#xff0c;你想最大化從矩陣中得到的分數。 你的得分方式為&#xff1a;每一行 中選取一個格子&#xff0c;選中坐標為 (r, c) 的格子會給你的總得分 增加 points[r][c] 。 然…

您有一個上云錦囊尚未領取!

前期&#xff0c;我們通過文章《確認過眼神&#xff1f;上云之路需要遇上對的人&#xff01;》向大家詳細介紹了阿里云咨詢與設計場景下的五款專家服務產品&#xff0c;企業可以通過這些專家服務產品解決了上云前的痛點。那么&#xff0c;當完成上云前的可行性評估與方案設計后…

怎么從運營轉到前端開發_我如何在16個月內從銷售人員轉到前端開發人員

怎么從運營轉到前端開發On August 18, 2015, I was on a one-way flight headed to Copenhagen from Toronto Pearson Airport. I was starting my two semester exchange at the Copenhagen Business school. 2015年8月18日&#xff0c;我乘坐單程飛機從多倫多皮爾遜機場前往哥…

Python os.chdir() 方法

概述 os.chdir() 方法用于改變當前工作目錄到指定的路徑。 語法 chdir()方法語法格式如下&#xff1a; os.chdir(path) 參數 path -- 要切換到的新路徑。 返回值 如果允許訪問返回 True , 否則返回False。 實例 以下實例演示了 chdir() 方法的使用&#xff1a; #!/usr/bin/pyth…

oracle認證考試_Oracle云認證–通過此3小時免費課程通過考試

oracle認證考試This Oracle Cloud Certification exam will take – on average – about one week of study to prepare for. Most people who seriously commit to their studies are ready to pass the exam within about four days.這項Oracle Cloud認證考試平均需要大約一…

git 修改遠程倉庫源

自己已經寫好了一個項目&#xff0c;想上傳到 github github 創建新項目 新建 README.md &#xff0c; LICENSE 本地項目添加 github 遠程倉庫源 不是git項目git remote add origin https://USERNAME:PASSWORDgithub.com/USERNAME/pro.git已是git項目&#xff0c;先刪除再添加 …

Docker 常用命令備忘錄

build鏡像docker build -t"name" . 復制代碼后臺運行docker run -d -i -t 14a21c118315 /bin/bash 復制代碼刪除鏡像docker image rmi -f 300de37c15f9 復制代碼停止運行的鏡像docker ps docker kill (id) 復制代碼進入鏡像docker attach 29f2ab8e517c(ps id) 復制…

mvp最小可行產品_最低可行產品–如何為您的項目建立MVP以及為什么要這樣做

mvp最小可行產品具有足夠功能的產品可以收集全面的定性反饋 (A product with just enough features to gather comprehensive qualitative feedback) Proof of concept, prototypes, wireframes, mockups… what actually constitutes a Minimum Viable Product (MVP)?概念驗證…

composer 更改為中國鏡像

composer 更改為中國鏡像 $ composer config -g repo.packagist composer https://packagist.phpcomposer.com 轉載于:https://www.cnblogs.com/love-snow/articles/8111410.html

人人都能學會的python編程教程(基礎篇)完整版

人人都能學會的python編程教程1&#xff1a;第一行代碼 人人都能學會的python編程教程2&#xff1a;數據類型和變量 人人都能學會的python編程教程3&#xff1a;字符串和編碼 人人都能學會的python編程教程4&#xff1a;關系運算符與循環 人人都能學會的python編程教程5&#x…

劍指 Offer 56 - I. 數組中數字出現的次數

一個整型數組 nums 里除兩個數字之外&#xff0c;其他數字都出現了兩次。請寫程序找出這兩個只出現一次的數字。要求時間復雜度是O(n)&#xff0c;空間復雜度是O(1)。 示例 1&#xff1a; 輸入&#xff1a;nums [4,1,4,6] 輸出&#xff1a;[1,6] 或 [6,1] 示例 2&#xff1a…

表達愛意的程序_如何像程序員一樣表達愛意??

表達愛意的程序Today is Valentines Day! &#x1f60d; 今天是情人節&#xff01; &#x1f60d; How nice would it be if you sent a Romantic Message every hour to your loved one? But even better... 如果您每小時向您所愛的人發送一封浪漫的短信&#xff0c;那將有多…

工作中的小問題

1、a標簽的選擇問題 需要修改帶class的a標簽的hover的文字顏色&#xff0c;方式如下 <style>a.egHyperlink:hover{color:red;} </style> <a href"#" class"egHyperlink">smile</a> 復制代碼2、hr分割線 需要一條粉紅色的分割線&am…

More DETAILS! PBR的下一個發展在哪里?

最近幾年圖形學社區對PBR的關注非常高&#xff0c;也許是由于Disney以及一些游戲引擎大廠的助推&#xff0c;也許是因為它可以被輕松集成進實時渲染的游戲引擎當中&#xff0c;也許是因為許多人發現現在只需要調幾個參數就能實現具有非常精細細節的表面著色了。反正現在網絡上隨…

sql server 2008 身份驗證失敗 18456

雙擊打開后加上 ;-m 然后以管理員方式 打開 SQLSERVER 2008 就可以已window身份登錄 不過還沒有完 右鍵 屬性 》安全性 更改為 sql server 和 window身份驗證模式 沒有sql server登陸賬號的話創建一個 然后把-m去掉就可以用帳號登錄了 轉載于:https://www.cnblogs.com/R…

js 兩個方法

//js in_array方法function in_array(all,one) { for(i0;i<all.length;i) { if(all[i] one) return true; } return false; } //js in_array方法/*** 一維數組去重方法** param arr 需要去重數組* returns {Array} 返回已經去重數組*/function unique(arr) {var ret [];va…