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.mzph.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…