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)

让我们开始建设 (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}>
				<input
					onChange={(e) => setUsername(e.target.value)}
					type="text"
					placeholder="Enter your username"
				/>
				<input
					onChange={(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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值