二手商品交易網(wǎng)站開發(fā)百度搜索引擎廣告
?🌈個人主頁:前端青山
🔥系列專欄:node.js篇
🔖人終將被年少不可得之物困其一生
依舊青山,本期給大家?guī)韓ode.js篇專欄內(nèi)容:node.js-入門指南:從零開始構建全棧應用
前言
大家好,我是青山。作為一名前端開發(fā)工程師,我一直在尋找一種能夠讓我同時掌握前后端開發(fā)的技術棧。Node.js 的出現(xiàn),無疑為我打開了新的大門。通過 Node.js,我們不僅可以在后端編寫 JavaScript 代碼,還可以輕松地與前端進行聯(lián)調(diào)。本文將帶你從零開始學習 Node.js,并結(jié)合 MongoDB 數(shù)據(jù)庫,構建一個簡單的全棧應用。
目錄
前言
一、Node.js 簡介
1.1 什么是 Node.js?
1.2 Node.js 的優(yōu)勢
1.3 安裝 Node.js
二、創(chuàng)建第一個 Node.js 應用
2.1 初始化項目
2.2 編寫第一個 Node.js 代碼
2.3 代碼解釋
三、連接 MongoDB 數(shù)據(jù)庫
3.1 什么是 MongoDB?
3.2 安裝 MongoDB
3.3 安裝 MongoDB 驅(qū)動
3.4 連接 MongoDB
3.5 代碼解釋
四、前端聯(lián)調(diào)
4.1 創(chuàng)建 Vue.js 項目
4.2 調(diào)用 Node.js API
4.3 代碼解釋
五、總結(jié)
一、Node.js 簡介
1.1 什么是 Node.js?
Node.js 是一個基于 Chrome V8 引擎的 JavaScript 運行環(huán)境。它允許開發(fā)者在服務器端運行 JavaScript 代碼,從而實現(xiàn)全棧開發(fā)。Node.js 采用事件驅(qū)動、非阻塞 I/O 模型,使其非常適合處理高并發(fā)的網(wǎng)絡應用。
1.2 Node.js 的優(yōu)勢
- 高性能:Node.js 使用 V8 引擎,性能非常出色。
- 異步 I/O:Node.js 采用事件驅(qū)動的非阻塞 I/O 模型,適合處理大量并發(fā)請求。
- 生態(tài)系統(tǒng)豐富:Node.js 擁有龐大的 npm 包管理器,提供了豐富的第三方庫。
- 跨平臺: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)建第一個 Node.js 應用
2.1 初始化項目
- 創(chuàng)建一個新的項目目錄:
mkdir my-first-node-app $ cd my-first-node-app
- 初始化項目,生成?
package.json
?文件:
npm init -y
2.2 編寫第一個 Node.js 代碼
- 在項目根目錄下創(chuàng)建一個?
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}/`);
});
- 運行項目:
node index.js
- 打開瀏覽器,訪問?
http://127.0.0.1:3000
,你會看到 "Hello, World!" 的輸出。
2.3 代碼解釋
require('http')
:引入 Node.js 內(nèi)置的 HTTP 模塊。http.createServer
:創(chuàng)建一個 HTTP 服務器。server.listen
:啟動服務器,監(jiān)聽指定的主機和端口。res.end
:發(fā)送響應內(nèi)容。
三、連接 MongoDB 數(shù)據(jù)庫
3.1 什么是 MongoDB?
MongoDB 是一個基于分布式文件存儲的開源數(shù)據(jù)庫系統(tǒng)。它支持動態(tài)查詢,可以存儲結(jié)構化、半結(jié)構化和非結(jié)構化的數(shù)據(jù)。MongoDB 使用 BSON(Binary JSON)格式存儲數(shù)據(jù),支持豐富的查詢語言和索引。
3.2 安裝 MongoDB
- 訪問?MongoDB 官網(wǎng),下載并安裝 MongoDB。
- 啟動 MongoDB 服務:
mongod
3.3 安裝 MongoDB 驅(qū)動
- 在項目根目錄下安裝 MongoDB 驅(qū)動:
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}/`);
});
- 運行項目:
node index.js
- 打開瀏覽器,訪問?
http://127.0.0.1:3000
,你會看到從 MongoDB 中獲取的數(shù)據(jù)。
3.5 代碼解釋
MongoClient
:MongoDB 的客戶端類,用于連接 MongoDB 服務器。client.connect()
:連接到 MongoDB 服務器。client.db('myFirstDatabase')
:選擇數(shù)據(jù)庫。database.collection('items')
:選擇集合。collection.find(query)
:查詢集合中的文檔。cursor.toArray()
:將查詢結(jié)果轉(zhuǎn)換為數(shù)組。
四、前端聯(lián)調(diào)
4.1 創(chuàng)建 Vue.js 項目
- 安裝 Vue CLI:
npm install -g @vue/cli
- 創(chuàng)建一個新的 Vue 項目:
vue create my-first-vue-app
- 進入項目目錄:
cd my-first-vue-app
- 啟動項目:
npm run serve
4.2 調(diào)用 Node.js API
- 在?
src/components
?目錄下創(chuàng)建一個?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 項目:
npm run serve
- 打開瀏覽器,訪問?
http://localhost:8080
,你會看到從 Node.js 后端獲取的數(shù)據(jù)。
4.3 代碼解釋
axios.get
:發(fā)送 GET 請求到 Node.js 后端。v-for
:循環(huán)渲染列表。created
:組件創(chuàng)建完成后執(zhí)行的生命周期鉤子。
五、總結(jié)
通過本文,我們從零開始學習了 Node.js 和 MongoDB 的基本概念,并構建了一個簡單的全棧應用。我們學會了如何創(chuàng)建一個 Node.js 服務器,連接 MongoDB 數(shù)據(jù)庫,以及如何在 Vue.js 前端項目中調(diào)用 Node.js API。
Node.js 和 MongoDB 的結(jié)合,為我們提供了強大的全棧開發(fā)能力。希望本文能幫助你快速上手 Node.js 和 MongoDB,開啟你的全棧開發(fā)之旅。
如果你有任何問題或建議,歡迎留言交流。期待在未來的文章中繼續(xù)與你分享更多技術知識。
希望這篇文章對你有所幫助!如果有任何疑問或需要進一步的解釋,請隨時聯(lián)系我。祝你在全棧開發(fā)的道路上越走越遠!