閱讀本篇文章時候,需要前端有一定基礎后,想要進階全堆疊,或者了解后端作業方式閱讀,能更好的提高,前后分離對接的理解,本篇只會,概況的帶領操作一遍,后端開發,簡單易懂,
文章目錄
- 一、搭建開發環境
- 二、搭建路由
- 路由和API的概念
- (一) 搭建基礎路由
- (二)創建controller 和model層
- (三)處理post請求
- 接下來完善并模擬所有的資料
一、搭建開發環境
tips 以下注釋 // 省略,,,, 均為省略未修改部分
我們先創建檔案夾nativBlog
然后使用 npm init -y 初始化一個專案

-
安裝nodemon 自動重啟node
npm i nodemon -D -
安裝cross-env 控制開發環境
npm i cross-env -D
按照下列創建并修改檔案,搭建一個基礎的nodeSever,并回傳一定資料
檔案結構
├─app.js
├─package.json
├─src
├─bin
| └www.js
www.js
const http = require('http')
const PORT = 8000
const serverHandle = require('../app')
const server = http.createServer(serverHandle)
server.listen(PORT)
console.log('已開啟 8000埠');
app.js
const serverHandle = (req,res)=>{
// 設定回傳格式 JSON
res.setHeader('Content-type','application/json')
//模擬一下假資料
const resData = {
name:'admin',
env:process.env.NODE_ENV
}
res.end(
JSON.stringify(resData)
)
}
module.exports = serverHandle
添加啟動命令
package.json
{
"name": "native-blog",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "cross-env NODE_ENV=dev nodemon ./bin/www.js",
"prd": "cross-env NODE_ENV=production nodemon ./bin/www.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"cross-env": "^7.0.3",
"nodemon": "^2.0.7"
}
}
運行一下
然后打開瀏覽器或者postman測驗一下
npm run dev

二、搭建路由
路由和API的概念
API:
前端和后端、不同端(子系統)之間對接的一個術語
前端只需要知道 url(路由)是什么,傳遞方式和引數,不需要知道如何實作
路由:
API的一部分,
后端系統內部的一個定義,
,比如要實作一個api,需要定義一個router,controller db model等等
(一) 搭建基礎路由
以下為我們需要建立的介面

我們區分blog和user2個部分建立檔案
├─src
| ├─router //處理路由
| | ├─blog.js
| | └user.js
blog.js
const handleBlogRouter = (req,res) =>{
console.log('method:',req.method);
console.log(' req.path:', req.path);
// 獲取博客串列
if(req.method ==='GET'&& req.path ==='/api/blog/list') {
console.log('進入2');
return {
msg:'這是獲取博客串列的介面'
}
}
// 獲取博客詳情
if(req.method === 'GET'&& req.path ==='/api/blog/detail') {
return {
msg:'這是獲取博客詳情的介面'
}
}
// 新建一篇博客
if(req.method === 'POST'&& req.path ==='/api/blog/new') {
return {
msg:'這是新建博客串列的介面'
}
}
// 更新博客串列
if(req.method === 'POST'&& req.path ==='/api/blog/update') {
return {
msg:'這是更新博客串列的介面'
}
}
// 洗掉博客串列
if(req.method === 'GET'&& req.path ==='/api/blog/del') {
return {
msg:'這是洗掉博客串列的介面'
}
}
}
module.exports = handleBlogRouter
user.js
const handleUserRouter = (req,res)=>{
// 登錄
if(req.method === 'POST' && req.path === '/api/user/login'){
return {
msg:'這是登錄的介面'
}
}
}
module.exports = handleUserRouter
修改一下原本的app.js 來處理請求
const querystring = require('querystring') //引入原生模塊決議get引數
const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
const serverHandle = (req,res)=>{
// 設定回傳格式 JSON
res.setHeader('Content-type','application/json')
// 獲取路徑
const url = req.url
req.path = url.split('?')[0]
// 決議query
req.query = querystring.parse(url.split('?')[0])
// 處理blog路由
const blogData= handleBlogRouter(req,res)
if(blogData){
res.end(
JSON.stringify(blogData)
)
return
}
// 處理user路由
const userData= handleUserRouter(req,res)
if(userData){
res.end(
JSON.stringify(userData)
)
return
}
// 未命中路由回傳404
res.writeHead(404,{"COntent-type":"text/plian"})
res.write("404 Not Found\n")
res.end()
}
module.exports = serverHandle
通過上步,我們簡單搭建了一套路由,然后用在psotman來測驗一下

OK,沒有問題,當然你需要每個介面都嘗試一下
(二)創建controller 和model層
檔案結構
├─src
| ├─router //處理路由
| | ├─blog.js
| | └user.js
| ├─model //建立資料模型
| | └resModel.js
| ├─controller //處理業務邏輯
| | ├─blog.js
| | └user.js
分清楚一個事實,就要分清層級,router只管路由的處理,www.js只管創建sever,controller只管業務邏輯的處理
model 處理回傳的資料結構
到這一步,還沒連接資料庫,但我們要假裝模擬一下真實的資料回傳
首先建立model
resModel.js
class BaseModel {
constructor(data, message) {
// 兼容判斷是否傳人2個引數
if (typeof data === 'string') {
this.message = data
data = null
message = null
}
if (data) {
this.data = data
}
if (message) {
this.message = message
}
}
}
//成功的資料模型
class SuccessModel extends BaseModel {
constructor(data, message) {
super(data, message)
this.errno = 0
}
}
// 失敗的資料模型
class ErrorModel extends BaseModel {
constructor(data, message) {
super(data, message)
this.errno = -1
}
}
module.exports = {
SuccessModel,
ErrorModel
}
其次建立controller層
先做個簡單的假資料模擬、
blog.js
const getList = (author,keyword) =>{
//模擬回傳的資料,用promise模擬異步資料庫操作
const promise = new Promise((resolve,reject)=>{
const data = [
{
id:1,
title:"標題A",
content:"內容A",
createTime:1600410168761,
author:"張三"
},
{
id:2,
title:"標題B",
content:"內容B",
createTime:1600410221493,
author:"李四"
}
]
resolve(data)
})
return promise
}
module.exports = {
getList
}
然后修改router下bolg.js的處理,修改一個介面來體驗一下
blog.js
//匯入controller
const {getList} = require('../controller/blog')
//匯入model
const {SuccessModel,ErrorModel} = require('../model/resModel')
......省略未修改部分
// 獲取博客串列
if(req.method ==='GET'&& req.path ==='/api/blog/list') {
const author = "張三"
const keyword = "標題A"
const result = getList(author,keyword)
return result.then(data =>{
return new SuccessModel(data,'請求成功')
})
}
......省略未修改部分
app.js
...省略未修改部分
const serverHandle = (req,res)=>{
...省略未修改部分
// 處理blog路由
const blogResult= handleBlogRouter(req,res)
if(blogResult){
blogResult.then(blogData =>{
if(blogData){
res.end(
JSON.stringify(blogData)
)
}
})
return
}
// // 處理user路由
const userResult= handleUserRouter(req,res)
if(userResult){
userResult.then(userData=>{
if(userData){
res.end(
JSON.stringify(userData)
)
return
}
})
}
...省略未修改部分
}
module.exports = serverHandle
修改完成后用postman來測驗

測驗成功,代表我們的模塊規劃沒有問題
(三)處理post請求
前面都是用的get,對于post我們還沒做任何處理,post是異步操作,所以我們需要用promise來處理一下
封裝一個下面方法來處理post
// 處理post請求
const getPostData = (req) => {
const promise = new Promise((resolve, reject) => {
// 不是post,get請求
if (req.method !== 'POST') {
resolve({})
return
}
// post請求處理, 如果回傳的格式不是json 回傳一個空
if (req.headers['content-type'] !== 'application/json') {
resolve({})
return
}
let postData = ''
// post資料其實是資料流,所以我們需要監聽拼接資料
req.on('data', chunk => {
postData += chunk.toString()
})
req.on('end', () => {
// 沒有資料回傳一個空
if (!postData) {
resolve({})
return
}
resolve(
JSON.parse(postData)
)
})
})
return promise
}
然后app.js完整代碼 如下,在處理路由前,先通過封裝的方法處理一下post請求
const querystring = require('querystring')
const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
// 處理post請求
const getPostData = (req) => {
const promise = new Promise((resolve, reject) => {
// 不是post,get請求
if (req.method !== 'POST') {
resolve({})
return
}
// post請求處理, 如果回傳的格式不是json 回傳一個空
if (req.headers['content-type'] !== 'application/json') {
resolve({})
return
}
let postData = ''
req.on('data', chunk => {
postData += chunk.toString()
})
req.on('end', () => {
// 沒有資料回傳一個空
if (!postData) {
resolve({})
return
}
resolve(
JSON.parse(postData)
)
})
})
return promise
}
const serverHandle = (req,res)=>{
// 設定回傳格式 JSON
res.setHeader('Content-type','application/json')
// 獲取路徑
const url = req.url
req.path = url.split('?')[0]
// 決議query
req.query = querystring.parse(url.split('?')[1])
// 處理post請求
getPostData(req).then(postData=>{
req.body = postData
// 處理blog路由
const blogResult= handleBlogRouter(req,res)
if(blogResult){
blogResult.then(blogData =>{
if(blogData){
res.end(
JSON.stringify(blogData)
)
}
})
return
}
// // 處理user路由
const userResult= handleUserRouter(req,res)
if(userResult){
userResult.then(userData=>{
if(userData){
res.end(
JSON.stringify(userData)
)
}
})
return
}
// 未命中路由回傳404
res.writeHead(404,{"COntent-type":"text/plian"})
res.write("404 Not Found\n")
res.end()
})
}
module.exports = serverHandle
之后修改一個post介面來測驗一下
controller
blog.js
...省略
const newBlog = (blogData = {}) =>{
// blogData 包含 title content
// 添加成功回傳添加id,
//模擬處理完成后回傳資料
const promise = new Promise((resolve,reject)=>{
const data = {
id:3
}
resolve(data)
})
return promise
}
module.exports = {
...省略
newBlog
}
router
blog.js
const {
...省略
newBlog} = require('../controller/blog')
...省略
// 新建一篇博客
if(req.method === 'POST'&& req.path ==='/api/blog/new') {
const result = newBlog(req.body)
return result.then(data =>{
return new SuccessModel(data,'添加成功')
})
}
...省略
通過postman測驗一下,

接下來完善并模擬所有的資料
controller
blog.js
const getList = (author,keyword) =>{
const promise = new Promise((resolve,reject)=>{
const data = [
{
id:1,
title:"標題A",
content:"內容A",
createTime:1600410168761,
author:"張三"
},
{
id:2,
title:"標題B",
content:"內容B",
createTime:1600410221493,
author:"李四"
}
]
resolve(data)
})
return promise
}
const getDetail = (id) =>{
const promise = new Promise((resolve,reject)=>{
const data = [
{
id:2,
title:"標題B",
content:"內容B",
createTime:1600410221493,
author:"李四"
}
]
resolve(data)
})
return promise
}
const newBlog = (blogData = {}) =>{
// blogData 包含 title content
// 添加成功回傳添加id,
const promise = new Promise((resolve,reject)=>{
const data = {
id:3
}
resolve(data)
})
return promise
}
const updateBlog = (id,blogData = {}) =>{
// id 就是要更新博客的 id
// blogData 是一個博客物件,包含 title content 屬性
const promise = new Promise((resolve,reject)=>{
resolve(true)
})
return promise
}
const delBlog = (id,author) =>{
// id 洗掉博客的id
const promise = new Promise((resolve,reject)=>{
resolve(true)
})
return promise
}
module.exports = {
getList,
getDetail,
updateBlog,
newBlog,
delBlog
}
user.js
const login = (username, password) =>{
const promise = new Promise((resolve,reject)=>{
resolve(false)
})
return promise
}
module.exports = {
login
}
router
blog.js
const {
getList,
getDetail,
updateBlog,
newBlog,
delBlog} = require('../controller/blog')
const {SuccessModel,ErrorModel} = require('../model/resModel')
const handleBlogRouter = (req,res) =>{
const method = req.method
const id = req.query.id
console.log('method:',req.method);
console.log(' req.path:', req.path);
// 獲取博客串列
if(method ==='GET'&& req.path ==='/api/blog/list') {
const author = req.query.author
const keyword =req.query.keyword
const result = getList(author,keyword)
return result.then(data =>{
return new SuccessModel(data,'請求成功')
})
}
// 獲取博客詳情
if(method === 'GET'&& req.path ==='/api/blog/detail') {
const result = getDetail(id)
return result.then(data =>{
return new SuccessModel(data,'請求成功')
})
}
// 新建一篇博客
if(method === 'POST'&& req.path ==='/api/blog/new') {
const result = newBlog(req.body)
return result.then(data =>{
return new SuccessModel(data,'添加成功')
})
}
// 更新博客串列
if(method === 'POST'&& req.path ==='/api/blog/update') {
const result = updateBlog(id,req.body)
return result.then(data =>{
if(data){
return new SuccessModel('修改成功')
} else {
return new ErrorModel('修改失敗')
}
})
}
// 洗掉博客串列
if(method === 'GET'&& req.path ==='/api/blog/del') {
const author = req.query.author
const result = delBlog(id,author)
return result.then(data =>{
if(data){
return new SuccessModel('洗掉成功')
} else {
return new ErrorModel('洗掉失敗')
}
})
}
}
module.exports = handleBlogRouter
user.js
const {login} = require('../controller/user')
const {SuccessModel,ErrorModel} = require('../model/resModel')
const handleUserRouter = (req,res)=>{
// 登錄
if(req.method === 'POST' && req.path === '/api/user/login'){
const {userName,passWord} = req.body
const result = login(userName,passWord)
return result.then(data =>{
if(data){
return new SuccessModel('登陸成功')
} else {
return new ErrorModel('登陸失敗')
}
})
}
}
module.exports = handleUserRouter
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/286782.html
標籤:其他
上一篇:50、路由vue-router
下一篇:【前后端分離】Springboot+Vue實作Kaptcha生成驗證碼、Graphics 2D隨機驗證碼(兩種樣式) | 通過Vue顯示到前端頁面
