mern技术栈好处?_如何开始使用MERN堆栈
mern技術棧好處?
介紹 (Introduction)
The MERN stack consists of MongoDB, Express, React / Redux, and Node.js. The MERN stack is one of the most popular JavaScript stacks for building modern single-page web applications.
MERN堆棧由MongoDB,Express,React / Redux和Node.js組成。 MERN堆棧是用于構建現代單頁Web應用程序的最受歡迎JavaScript堆棧之一。
In this tutorial, you will build a todo application that uses a RESTful API, which you will also build later in this tutorial.
在本教程中,您將構建一個使用RESTful API的todo應用程序 ,您還將在本教程的稍后部分中構建該應用程序 。
先決條件 (Prerequisites)
To follow along with this tutorial, you will need to install node and npm on your computer. If you do not have node installed, follow the instructions on the nodejs website. You will also need a code editor that you are familiar with, preferably one that has support for JavaScript code highlighting.
要遵循本教程,您將需要在計算機上安裝node和npm。 如果尚未安裝節點,請按照nodejs網站上的說明進行操作。 您還需要一個熟悉的代碼編輯器,最好是一個支持JavaScript代碼突出顯示的代碼編輯器。
應用程序代碼設置 (Application Code Setup)
Let’s start with the setup. Open your terminal and create a new file directory in any convienient location on your local machine. You can name it anything but in this example it is called Todo.
讓我們從設置開始。 打開終端,并在本地計算機上任何方便的位置創建一個新的文件目錄。 您可以給它起任何名字,但在本示例中,它稱為Todo 。
- mkdir Todo 麥克迪爾·托多
Now enter into that file directory
現在進入該文件目錄
- cd Todo cd待辦事項
The next step is to initialize the project with a package.json file. This file will contain some information about our app and the dependencies that it needs to run. You can use npm init and follow the instructions when prompted, or you can use npm init -yto use the default values.
下一步是使用package.json文件初始化項目。 該文件將包含有關我們的應用程序以及它需要運行的依賴項的一些信息。 您可以使用npm init并按照提示進行操作,也可以使用npm init -y使用默認值。
節點服務器設置 (Node Server Setup)
To run our javascript code on the backend we need to spin up a server that will compile our code. The server can be created in two ways: first is to use the built in http module in node; second is to make use of the expressjs framework.
要在后端運行我們的javascript代碼,我們需要啟動一個服務器來編譯我們的代碼。 可以通過兩種方式創建服務器:首先是在節點中使用內置的http模塊。 其次是利用expressjs框架 。
This tutorial will use expressjs. It is a nodejs HTTP framework that handles a lot of things out of the box and requires very little code to create fully functional RESTful APIs. To use express, install it using npm:
本教程將使用expressjs。 它是一個nodejs HTTP框架,可以處理很多現成的事情,并且只需很少的代碼即可創建功能齊全的RESTful API。 要使用express,請使用npm安裝它:
- npm install express npm安裝快遞
Now create a file index.js and type the code below into it and save:
現在創建一個文件index.js并在其中鍵入以下代碼并保存:
const express = require('express'); require('dotenv').config();const app = express();const port = process.env.PORT || 5000;app.use((req, res, next) => {res.header("Access-Control-Allow-Origin", "*");res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");next(); });app.use((req, res, next) => {res.send('Welcome to Express'); });app.listen(port, () => {console.log(`Server running on port ${port}`) });This snipped from the code above helps handle CORS related issues that you might face when trying to access the api from different domains during development and testing:
從上面的代碼中摘錄的代碼有助于解決在開發和測試過程中嘗試從不同域訪問api時可能遇到的CORS相關問題:
app.use((req, res, next) => {res.header("Access-Control-Allow-Origin", "*");res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");next(); });It’s time to start our server to see if it works. Open your terminal in the same directory as your index.js file and type:
現在是時候啟動我們的服務器以查看其是否正常工作了。 在與index.js文件相同的目錄中打開終端,然后鍵入:
- node index.js 節點index.js
If every thing goes well, you should see Server running on port 5000 in your terminal.
如果一切順利,您應該在終端中看到服務器在端口5000上運行 。
路線 (Routes)
There are three things that the app needs to do: create a task; view all tasks; and delete a completed task. For each task, we need to create routes that will define various endpoints that the todo app will depend on. So let’s create a folder routes and create a file api.js with the following code in it.
應用程序需要做三件事:創建任務; 查看所有任務; 并刪除已完成的任務。 對于每個任務,我們需要創建路由來定義待辦事項應用程序依賴的各種端點。 因此,讓我們創建一個文件夾routes并使用以下代碼創建一個文件api.js
- mkdir routes mkdir路線
Edit api.js and paste the following code in it:
編輯api.js并在其中粘貼以下代碼:
const express = require ('express'); const router = express.Router();router.get('/todos', (req, res, next) => {});router.post('/todos', (req, res, next) => {});router.delete('/todos/:id', (req, res, next) => {})module.exports = router;楷模 (Models)
Now comes the interesting part, since the app is going to make use of mongodb which is a noSql database, we need to create a model and a schema. Models are defined using the Schema interface. The Schema allows you to define the fields stored in each document along with their validation requirements and default values. In essence the Schema is a blueprint of how the database will be constructed. In addition, you can define static and instance helper methods to make it easier to work with your data types, and also virtual properties that you can use like any other field, but which aren’t actually stored in the database.
現在介紹有趣的部分,因為該應用程序將使用mongodb(這是一個noSql數據庫),因此我們需要創建一個模型和一個架構。 使用Schema接口定義模型。 通過該架構,您可以定義每個文檔中存儲的字段以及它們的驗證要求和默認值。 從本質上講,該架構是如何構建數據庫的藍圖。 另外,您可以定義靜態和實例幫助器方法以使您更輕松地使用數據類型,以及可以像其他任何字段一樣使用但實際上未存儲在數據庫中的虛擬屬性。
To create a Schema and a model, install mongoose which is a node package that makes working with mongodb easier.
要創建模式和模型,請安裝mongoose ,這是一個使mongodb易于使用的節點程序包。
- npm install mongoose npm安裝貓鼬
Create a new folder in your root directory and name it models. Inside it create a file and name it todo.js with the following code in it:
在您的根目錄中創建一個新文件夾,并將其命名為models 。 在其中創建一個文件,并使用以下代碼將其命名為todo.js :
- mkdir models mkdir模型
Paste the following into todo.js with your text editor:
使用您的文本編輯器將以下內容粘貼到todo.js :
const mongoose = require('mongoose'); const Schema = mongoose.Schema;//create schema for todo const TodoSchema = new Schema({action: {type: String,required: [true, 'The todo text field is required']} })//create model for todo const Todo = mongoose.model('todo', TodoSchema);module.exports = Todo;Now we need to update our routes to make use of the new model.
現在,我們需要更新路線以使用新模型。
const express = require ('express'); const router = express.Router(); const Todo = require('../models/todo');router.get('/todos', (req, res, next) => {//this will return all the data, exposing only the id and action field to the clientTodo.find({}, 'action').then(data => res.json(data)).catch(next) });router.post('/todos', (req, res, next) => {if(req.body.action){Todo.create(req.body).then(data => res.json(data)).catch(next)}else {res.json({error: "The input field is empty"})} });router.delete('/todos/:id', (req, res, next) => {Todo.findOneAndDelete({"_id": req.params.id}).then(data => res.json(data)).catch(next) })module.exports = router;數據庫 (Database)
We need a database where we will store our data. For this we will make use of mlab. Follow this doc to get started with mlab. After setting up your database you need to update index.js file with the following code:
我們需要一個數據庫來存儲數據。 為此,我們將使用mlab。 按照此文檔開始使用mlab。 設置數據庫后,您需要使用以下代碼更新index.js文件:
const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const routes = require('./routes/api'); const path = require('path'); require('dotenv').config();const app = express();const port = process.env.PORT || 5000;//connect to the database mongoose.connect(process.env.DB, { useNewUrlParser: true }).then(() => console.log(`Database connected successfully`)).catch(err => console.log(err));//since mongoose promise is depreciated, we overide it with node's promise mongoose.Promise = global.Promise;app.use((req, res, next) => {res.header("Access-Control-Allow-Origin", "*");res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");next(); });app.use(bodyParser.json());app.use('/api', routes);app.use((err, req, res, next) => {console.log(err);next(); });app.listen(port, () => {console.log(`Server running on port ${port}`) });In the code above we made use of process.env to access environment variables, which need to be created. Create a file in your root directory with name .env and edit:
在上面的代碼中,我們使用了process.env來訪問需要創建的環境變量。 在根目錄中創建一個名為.env的文件,然后編輯:
DB = ‘mongodb://<USER\>:<PASSWORD\>@ds039950.mlab.com:39950/todo’
DB ='mongodb:// <USER \>:<PASSWORD \> @ ds039950.mlab.com:39950 / todo'
Make sure you use your own mongodb URL from mlab after you created your database and user. Replace <USER> with the username and <PASSWORD> with the password of the user you created. To work with environment variable we have to install a node package called dotenv that makes sure we have access to environment variable stored in the .env file.
創建數據庫和用戶后,請確保使用來自mlab的自己的mongodb URL。 將<USER>替換為用戶名,并將<PASSWORD>替換為您創建的用戶的密碼。 要使用環境變量,我們必須安裝名為dotenv的節點包,以確保我們可以訪問存儲在.env文件中的環境變量。
- npm install dotenv npm安裝dotenv
Then require and configure it in index.js:
然后要求并在index.js配置它:
require('dotenv').config()Using environment variables instead of writing credentials to the application code directly can hide sensitive information from our versioning system. It is considered a best practice to separate configuration and secret data from application code in this manner.
使用環境變量而不是直接將憑據寫入應用程序代碼可以從我們的版本控制系統中隱藏敏感信息。 以這種方式從應用程序代碼中分離配置和機密數據被認為是最佳實踐。
測試Api (Testing Api)
This is the part we start trying out things to make sure our RESTful api is working. Since our frontend is not ready yet, we can make use of some api development clients to test our code. You can use of Postman or Insomnia or if there is another client that you prefer for testing APIs, you can use of it.
這是我們開始嘗試確保RESTful api正常工作的部分。 由于我們的前端尚未準備好,我們可以利用一些api開發客戶端來測試我們的代碼。 您可以使用Postman或Insomnia ,也可以使用其他客戶端來測試API。
Start your server using the command:
使用以下命令啟動服務器:
- node index.js 節點index.js
Now open your client, create a get method and navigate to http://localhost:5000/api/todos
現在打開您的客戶端,創建一個get方法并導航到http:// localhost:5000 / api / todos
You should test all the api endpoints and make sure they are working. For the endpoints that require body, you should send json back with the necessary fields since it’s what we setup in our code.
您應該測試所有api端點,并確保它們正常工作。 對于需要正文的端點,您應該將json與必要的字段一起發送回去,因為這是我們在代碼中設置的。
創建前端 (Creating the Frontend)
Since we are done with the functionality we want from our api, it is time to create an interface for the client to interact with the api. To start out with the frontend of the todo app, we will use the create-react-app command to scaffold our app.
由于我們已經完成了api所需的功能,因此現在該為客戶端創建一個與api進行交互的接口了。 首先從todo應用程序的前端開始,我們將使用create-react-app命令來搭建我們的應用程序。
In the same root directory as your backend code, which is the todo directory, run:
在與后端代碼相同的根目錄(即todo目錄)中,運行:
- create-react-app client 創建React應用程序客戶端
This will create a new folder in your todo directory called client, where you will add all the react code.
這將在todo目錄中創建一個名為client的新文件夾,您將在其中添加所有React代碼。
運行React應用 (Running the React App)
Before testing the react app, there are a number od dependencies that need to be installed.
在測試React應用之前,需要安裝一些od依賴項。
Install concurrently as a dev dependency:
作為開發依賴項并發安裝:
- npm install concurrently --save-dev npm同時安裝--save-dev
Concurrently is used to run more than one command simultaneously from the same terminal window.
同時用于從同一終端窗口同時運行多個命令。
Install nodemon as a dev dependency:
安裝nodemon作為dev依賴項:
- npm install nodemon --save-dev npm install nodemon --save-dev
Nodemon is used to run the server and monitor it as well. If there is any change in the server code, nodemon will restart it automatically with the new changes.
Nodemon用于運行服務器并對其進行監視。 如果服務器代碼有任何更改,nodemon將使用新更改自動重新啟動它。
Open your terminal and run npm run dev and make sure you are in the todo directory and not in the client directory. Your app should be open and running on localhost:3000.
打開終端并運行npm run dev ,并確保您位于todo目錄中,而不在client目錄中。 您的應用應已打開并在localhost:3000上運行。
創建您的React組件 (Creating your React Components)
One of the advantages of react is that it makes use of components, which are reusable and also makes code modular. For our todo app, there will be two state components and one stateless component. Inside your src folder create another folder called components and inside it create three files Input.js, ListTodo.js and Todo.js.
react的優點之一是它利用了可重用的組件,并使代碼模塊化。 對于我們的待辦事項應用程序,將有兩個狀態組件和一個無狀態組件。 在src文件夾中,創建另一個名為components文件夾,并在其中創建三個文件Input.js , ListTodo.js和Todo.js
Open Input.js file and paste the following
打開Input.js文件并粘貼以下內容
import React, { Component } from 'react'; import axios from 'axios';class Input extends Component {state = {action: ""}addTodo = () => {const task = {action: this.state.action}if(task.action && task.action.length > 0){axios.post('/api/todos', task).then(res => {if(res.data){this.props.getTodos();this.setState({action: ""})}}).catch(err => console.log(err))}else {console.log('input field required')}}handleChange = (e) => {this.setState({action: e.target.value})}render() {let { action } = this.state;return (<div><input type="text" onChange={this.handleChange} value={action} /><button onClick={this.addTodo}>add todo</button></div>)} }export default InputTo make use of axios, which is a Promise based HTTP client for the browser and node.js, you need to cd into your client from your terminal and run yarn add axios or npm install axios
要使用axios,這是瀏覽器和node.js的基于Promise的HTTP客戶端,您需要從終端cd進入客戶端,然后運行yarn add axios或npm install axios
- cd client cd客戶端
- npm install axios npm安裝axios
After that open your ListTodo.js file and paste the following code
之后,打開您的ListTodo.js文件并粘貼以下代碼
import React from 'react';const ListTodo = ({ todos, deleteTodo }) => {return (<ul>{todos &&todos.length > 0 ?(todos.map(todo => {return (<li key={todo._id} onClick={() => deleteTodo(todo._id)}>{todo.action}</li>)})):(<li>No todo(s) left</li>)}</ul>) }export default ListTodoThen in your Todo.js file you write the following code
然后在您的Todo.js文件中編寫以下代碼
import React, {Component} from 'react'; import axios from 'axios';import Input from './Input'; import ListTodo from './ListTodo';class Todo extends Component {state = {todos: []}componentDidMount(){this.getTodos();}getTodos = () => {axios.get('/api/todos').then(res => {if(res.data){this.setState({todos: res.data})}}).catch(err => console.log(err))}deleteTodo = (id) => {axios.delete(`/api/todos/${id}`).then(res => {if(res.data){this.getTodos()}}).catch(err => console.log(err))}render() {let { todos } = this.state;return(<div><h1>My Todo(s)</h1><Input getTodos={this.getTodos}/><ListTodo todos={todos} deleteTodo={this.deleteTodo}/></div>)} }export default Todo;We need to make little adjustment to our react code. Delete the logo and adjust our App.js to look like this.
我們需要對React代碼進行很少的調整。 刪除徽標并調整我們的App.js使其如下所示。
import React from 'react';import Todo from './components/Todo'; import './App.css';const App = () => {return (<div className="App"><Todo /></div>); }export default App;Then paste the following code into App.css:
然后將以下代碼粘貼到App.css :
.App {text-align: center;font-size: calc(10px + 2vmin);width: 60%;margin-left: auto;margin-right: auto; }input {height: 40px;width: 50%;border: none;border-bottom: 2px #101113 solid;background: none;font-size: 1.5rem;color: #787a80; }input:focus {outline: none; }button {width: 25%;height: 45px;border: none;margin-left: 10px;font-size: 25px;background: #101113;border-radius: 5px;color: #787a80;cursor: pointer; }button:focus {outline: none; }ul {list-style: none;text-align: left;padding: 15px;background: #171a1f;border-radius: 5px; }li {padding: 15px;font-size: 1.5rem;margin-bottom: 15px;background: #282c34;border-radius: 5px;overflow-wrap: break-word;cursor: pointer; }@media only screen and (min-width: 300px) {.App {width: 80%;}input {width: 100%}button {width: 100%;margin-top: 15px;margin-left: 0;} }@media only screen and (min-width: 640px) {.App {width: 60%;}input {width: 50%;}button {width: 30%;margin-left: 10px;margin-top: 0;} }Also in index.css add the following rules:
同樣在index.css添加以下規則:
body {margin: 0;padding: 0;font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen","Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;box-sizing: border-box;background-color: #282c34;color: #787a80; }code {font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",monospace; }Assuming no errors when saving all these files, the todo app should be ready and fully functional with the functionality discussed earlier: creating a task, deleting a task and viewing all your tasks.
假設保存所有這些文件時都沒有錯誤,那么todo應用程序應該已經準備就緒并且可以使用前面討論的功能完全正常運行:創建任務,刪除任務并查看所有任務。
結論 (Conclusion)
In this tutorial, you created a todo app using the MERN stack. You wrote a frontend application using React that communicates with a backend application written using expressjs. You also created a Mongodb backend for storing tasks in a database.
在本教程中,您使用MERN堆棧創建了一個todo應用程序。 您使用React編寫了一個前端應用程序,該前端應用程序與使用expressjs編寫的后端應用程序進行通信。 您還創建了一個Mongodb后端,用于將任務存儲在數據庫中。
翻譯自: https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack
mern技術棧好處?
總結
以上是生活随笔為你收集整理的mern技术栈好处?_如何开始使用MERN堆栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 调用 delphi_【java
- 下一篇: Environment Mapping