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.
注意:在開始我們的項目之前,必須在您的計算機上安裝node
。 node
還為我們提供了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
express
: "Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web applications" - Express Documentationexpress
:“ Express是一個最小且靈活的Node.js Web應用程序框架,為Web應用程序提供了一組強大的功能”-Express 文檔cors
: "CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options" - cors Documentationcors
:“ CORS是一個node.js軟件包,用于提供可用于通過各種選項啟用CORS的Connect / Express中間件” -cors文檔mongoose
: "Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks" - Mongoose Documentationmongoose
:“ Mongoose是一個旨在在異步環境中工作的MongoDB對象建模工具。Mongoose同時支持promise和回調。”- Mongoose文檔body-parser
: "Node.js body parsing middleware." - body-parser Documentationbody-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.
useState
和useEffect
掛鉤用于處理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?
如果您想了解更多有關useState
和useEffect
,請查看本文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
指定要安裝的引擎(如node
和npm
的版本。
推送到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