wordpress建的網(wǎng)站打開太慢優(yōu)化大師win10能用嗎
?🌈個(gè)人主頁(yè):前端青山
🔥系列專欄:node.js篇
🔖人終將被年少不可得之物困其一生
依舊青山,本期給大家?guī)韓ode.js篇專欄內(nèi)容:node.js-入門指南:從零開始構(gòu)建全棧應(yīng)用
前言
大家好,我是青山。作為一名前端開發(fā)工程師,我一直在尋找一種能夠讓我同時(shí)掌握前后端開發(fā)的技術(shù)棧。Node.js 的出現(xiàn),無疑為我打開了新的大門。通過 Node.js,我們不僅可以在后端編寫 JavaScript 代碼,還可以輕松地與前端進(jìn)行聯(lián)調(diào)。本文將帶你從零開始學(xué)習(xí) Node.js,并結(jié)合 MongoDB 數(shù)據(jù)庫(kù),構(gòu)建一個(gè)簡(jiǎn)單的全棧應(yīng)用。
目錄
前言
一、Node.js 簡(jiǎn)介
1.1 什么是 Node.js?
1.2 Node.js 的優(yōu)勢(shì)
1.3 安裝 Node.js
二、創(chuàng)建第一個(gè) Node.js 應(yīng)用
2.1 初始化項(xiàng)目
2.2 編寫第一個(gè) Node.js 代碼
2.3 代碼解釋
三、連接 MongoDB 數(shù)據(jù)庫(kù)
3.1 什么是 MongoDB?
3.2 安裝 MongoDB
3.3 安裝 MongoDB 驅(qū)動(dòng)
3.4 連接 MongoDB
3.5 代碼解釋
四、前端聯(lián)調(diào)
4.1 創(chuàng)建 Vue.js 項(xiàng)目
4.2 調(diào)用 Node.js API
4.3 代碼解釋
五、總結(jié)
一、Node.js 簡(jiǎn)介
1.1 什么是 Node.js?
Node.js 是一個(gè)基于 Chrome V8 引擎的 JavaScript 運(yùn)行環(huán)境。它允許開發(fā)者在服務(wù)器端運(yùn)行 JavaScript 代碼,從而實(shí)現(xiàn)全棧開發(fā)。Node.js 采用事件驅(qū)動(dòng)、非阻塞 I/O 模型,使其非常適合處理高并發(fā)的網(wǎng)絡(luò)應(yīng)用。
1.2 Node.js 的優(yōu)勢(shì)
- 高性能:Node.js 使用 V8 引擎,性能非常出色。
- 異步 I/O:Node.js 采用事件驅(qū)動(dòng)的非阻塞 I/O 模型,適合處理大量并發(fā)請(qǐng)求。
- 生態(tài)系統(tǒng)豐富:Node.js 擁有龐大的 npm 包管理器,提供了豐富的第三方庫(kù)。
- 跨平臺(tái):Node.js 支持 Windows、Linux 和 macOS 等多種操作系統(tǒng)。
1.3 安裝 Node.js
- 訪問?Node.js 官網(wǎng),下載最新版本的 Node.js。
- 按照安裝向?qū)瓿砂惭b。
- 打開命令行工具,輸入?
node -v
?和?npm -v
,檢查 Node.js 和 npm 是否安裝成功。
node -v v14.17.0 $ npm -v 6.14.13
二、創(chuàng)建第一個(gè) Node.js 應(yīng)用
2.1 初始化項(xiàng)目
- 創(chuàng)建一個(gè)新的項(xiàng)目目錄:
mkdir my-first-node-app $ cd my-first-node-app
- 初始化項(xiàng)目,生成?
package.json
?文件:
npm init -y
2.2 編寫第一個(gè) Node.js 代碼
- 在項(xiàng)目根目錄下創(chuàng)建一個(gè)?
index.js
?文件,編寫以下代碼:
// index.js
const http = require('http');const hostname = '127.0.0.1';
const port = 3000;const server = http.createServer((req, res) => {res.statusCode = 200;res.setHeader('Content-Type', 'text/plain');res.end('Hello, World!\n');
});server.listen(port, hostname, () => {console.log(`Server running at http://${hostname}:${port}/`);
});
- 運(yùn)行項(xiàng)目:
node index.js
- 打開瀏覽器,訪問?
http://127.0.0.1:3000
,你會(huì)看到 "Hello, World!" 的輸出。
2.3 代碼解釋
require('http')
:引入 Node.js 內(nèi)置的 HTTP 模塊。http.createServer
:創(chuàng)建一個(gè) HTTP 服務(wù)器。server.listen
:啟動(dòng)服務(wù)器,監(jiān)聽指定的主機(jī)和端口。res.end
:發(fā)送響應(yīng)內(nèi)容。
三、連接 MongoDB 數(shù)據(jù)庫(kù)
3.1 什么是 MongoDB?
MongoDB 是一個(gè)基于分布式文件存儲(chǔ)的開源數(shù)據(jù)庫(kù)系統(tǒng)。它支持動(dòng)態(tài)查詢,可以存儲(chǔ)結(jié)構(gòu)化、半結(jié)構(gòu)化和非結(jié)構(gòu)化的數(shù)據(jù)。MongoDB 使用 BSON(Binary JSON)格式存儲(chǔ)數(shù)據(jù),支持豐富的查詢語言和索引。
3.2 安裝 MongoDB
- 訪問?MongoDB 官網(wǎng),下載并安裝 MongoDB。
- 啟動(dòng) MongoDB 服務(wù):
mongod
3.3 安裝 MongoDB 驅(qū)動(dòng)
- 在項(xiàng)目根目錄下安裝 MongoDB 驅(qū)動(dòng):
npm install mongodb
3.4 連接 MongoDB
- 修改?
index.js
?文件,添加連接 MongoDB 的代碼:
// index.js
const http = require('http');
const { MongoClient } = require('mongodb');const hostname = '127.0.0.1';
const port = 3000;
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });const server = http.createServer(async (req, res) => {try {await client.connect();console.log('Connected to MongoDB');const database = client.db('myFirstDatabase');const collection = database.collection('items');const query = {};const cursor = collection.find(query);if ((await cursor.count()) === 0) {res.statusCode = 200;res.setHeader('Content-Type', 'text/plain');res.end('No items found\n');} else {const items = await cursor.toArray();res.statusCode = 200;res.setHeader('Content-Type', 'application/json');res.end(JSON.stringify(items));}} catch (err) {console.error(err);res.statusCode = 500;res.setHeader('Content-Type', 'text/plain');res.end('Internal Server Error\n');} finally {await client.close();}
});server.listen(port, hostname, () => {console.log(`Server running at http://${hostname}:${port}/`);
});
- 運(yùn)行項(xiàng)目:
node index.js
- 打開瀏覽器,訪問?
http://127.0.0.1:3000
,你會(huì)看到從 MongoDB 中獲取的數(shù)據(jù)。
3.5 代碼解釋
MongoClient
:MongoDB 的客戶端類,用于連接 MongoDB 服務(wù)器。client.connect()
:連接到 MongoDB 服務(wù)器。client.db('myFirstDatabase')
:選擇數(shù)據(jù)庫(kù)。database.collection('items')
:選擇集合。collection.find(query)
:查詢集合中的文檔。cursor.toArray()
:將查詢結(jié)果轉(zhuǎn)換為數(shù)組。
四、前端聯(lián)調(diào)
4.1 創(chuàng)建 Vue.js 項(xiàng)目
- 安裝 Vue CLI:
npm install -g @vue/cli
- 創(chuàng)建一個(gè)新的 Vue 項(xiàng)目:
vue create my-first-vue-app
- 進(jìn)入項(xiàng)目目錄:
cd my-first-vue-app
- 啟動(dòng)項(xiàng)目:
npm run serve
4.2 調(diào)用 Node.js API
- 在?
src/components
?目錄下創(chuàng)建一個(gè)?HelloWorld.vue
?組件:
<template><div class="hello"><h1>{{ msg }}</h1><ul><li v-for="item in items" :key="item._id">{{ item.name }}</li></ul></div>
</template><script>
import axios from 'axios';export default {name: 'HelloWorld',props: {msg: String,},data() {return {items: [],};},async created() {try {const response = await axios.get('http://127.0.0.1:3000');this.items = response.data;} catch (error) {console.error(error);}},
};
</script><style scoped>
.hello {text-align: center;
}
</style>
- 在?
src/App.vue
?中使用?HelloWorld
?組件:
<template><div id="app"><img alt="Vue logo" src="./assets/logo.png"><HelloWorld msg="Welcome to Your Vue.js + Node.js App"/></div>
</template><script>
import HelloWorld from './components/HelloWorld.vue';export default {name: 'App',components: {HelloWorld,},
};
</script><style>
#app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px;
}
</style>
- 安裝?
axios
:
npm install axios
- 重啟 Vue 項(xiàng)目:
npm run serve
- 打開瀏覽器,訪問?
http://localhost:8080
,你會(huì)看到從 Node.js 后端獲取的數(shù)據(jù)。
4.3 代碼解釋
axios.get
:發(fā)送 GET 請(qǐng)求到 Node.js 后端。v-for
:循環(huán)渲染列表。created
:組件創(chuàng)建完成后執(zhí)行的生命周期鉤子。
五、總結(jié)
通過本文,我們從零開始學(xué)習(xí)了 Node.js 和 MongoDB 的基本概念,并構(gòu)建了一個(gè)簡(jiǎn)單的全棧應(yīng)用。我們學(xué)會(huì)了如何創(chuàng)建一個(gè) Node.js 服務(wù)器,連接 MongoDB 數(shù)據(jù)庫(kù),以及如何在 Vue.js 前端項(xiàng)目中調(diào)用 Node.js API。
Node.js 和 MongoDB 的結(jié)合,為我們提供了強(qiáng)大的全棧開發(fā)能力。希望本文能幫助你快速上手 Node.js 和 MongoDB,開啟你的全棧開發(fā)之旅。
如果你有任何問題或建議,歡迎留言交流。期待在未來的文章中繼續(xù)與你分享更多技術(shù)知識(shí)。
希望這篇文章對(duì)你有所幫助!如果有任何疑問或需要進(jìn)一步的解釋,請(qǐng)隨時(shí)聯(lián)系我。祝你在全棧開發(fā)的道路上越走越遠(yuǎn)!