使用node搭建服務器,用到了現在比較流行的框架koa。
1、初始化package.json
npm init -y
2、安裝koa2
npm i koa --save
3、搭建服務器
const Koa = require('koa')
const app = new Koa()
app.use( async(ctx) => {
ctx.body = "hello world"
})
app.listen(3000, () => {
console.log('demo2 is run')
})
4、直接運行
node index.js
5、加入get或者post請求
app.use(async(ctx) => {
if (ctx.url === '/' && ctx.method === 'GET') {
let html = `
<h2>This is demo2</h2>
<form method="POST" action="/">
<p>username:</p>
<input name="username">
<p>age:</p>
<input name="age">
<p>website</p>
<input name="website">
<button type="submit">submit</button>
</form>
`
ctx.body = html
} else if (ctx.url === '/' && ctx.method === 'POST') {
let postData = await parsePostDate(ctx)
ctx.body = postData
} else {
ctx.body = '<h2>404</h2>'
}
})
const parsePostDate = (ctx) => {
return new Promise((resolve, reject) => {
try{
let postData = ""
ctx.req.on('data', (data) => {
postData += data
})
ctx.req.addListener("end", function() {
let parseData = parseQueryStr(postData)
resolve(parseData)
})
} catch(error) {
reject(error)
}
})
}
const parseQueryStr = (queryStr) => {
const queryData = {}
const queryStrList = queryStr.split('&')
console.log(queryStrList)
for (let [index,queryStr] of queryStrList.entries()) {
let itemList = queryStr.split('=')
console.log(itemList)
queryData[itemList[0]] = decodeURIComponent(itemList[1])
}
return queryData
}
6、上面簡單介紹了koa怎么開啟簡單的服務器,但是koa的強大之處在於能夠加入很多好用的中間件
7、加入koa-bodyparser中間件簡化post請求后
app.use(async(ctx) => {
if (ctx.url === '/' && ctx.method === 'GET') {
let html = `
<h2>This is demo2</h2>
<form method="POST" action="/">
<p>username:</p>
<input name="username">
<p>age:</p>
<input name="age">
<p>website</p>
<input name="website">
<button type="submit">submit</button>
</form>
`
ctx.body = html
} else if (ctx.url === '/' && ctx.method === 'POST') {
let postData = ctx.request.body
ctx.body = postData
} else {
ctx.body = '<h2>404</h2>'
}
})
8、加入koa-router中間件簡化請求判斷
router
.get('/', (ctx, next) => {
let html = `
<h2>This is demo2</h2>
<form method="POST" action="/">
<p>username:</p>
<input name="username">
<p>age:</p>
<input name="age">
<p>website</p>
<input name="website">
<button type="submit">submit</button>
</form>
`
ctx.body = html
})
.post('/',(ctx, next) => {
let postData = ctx.request.body
ctx.body = postData
})
app
.use(router.routes())
.use(router.allowedMethods())
9、引入koa2-cors中間件,設置請求跨域與請求類型
app.use(cors({
origin: function (ctx) {
if (ctx.url === '/test') {
return "*"; // 允許來自所有域名請求
}
return 'http://localhost:8080'; / 這樣就能只允許 http://localhost:8080 這個域名的請求了
},
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
10、加入koa-static中間件,服務器可訪問靜態文件
// 引入node的path方便一些
const path = require('path')
app.use(static((path.join(__dirname, 'images'))))
11、還可以引入koa-send實現文件下載
router.get('/download', async function (ctx) {
// 為了方便演示,這里直接下載index頁面
var fileName = 'index.html';
// Set Content-Disposition to "attachment" to signal the client to prompt for download.
// Optionally specify the filename of the download.
// 設置實體頭(表示消息體的附加信息的頭字段),提示瀏覽器以文件下載的方式打開
// 也可以直接設置 ctx.set("Content-disposition", "attachment; filename=" + fileName);
ctx.attachment(fileName);
await send(ctx, fileName, { root: __dirname + '/public' });
});
12、服務器整體構建完成,那么就要鏈接數據庫(請自行在電腦上安裝mongodb,https://www.mongodb.com/)
13、加入mongoose依賴鏈接本地的mangodb
// 直接在index.js下引入
const mongoose = require('mongoose') var dbUrl = `mongodb://127.0.0.1:27017/test` mongoose.connect(dbUrl, {useNewUrlParser:true} ,(err) => { if (err) { console.log('Mongoose connection error: ' + err.message) } else { console.log('數據庫連接成功') } }) mongoose .connection .on('disconnected', function () { console.log('Mongoose connection disconnected') }) module.exports = mongoose
14、mongoose的增刪改查,mongoose都是要先創建一個圖表(Schema)然后再對其進行操作
const mongoose = require('mongoose')
// 創圖表
var schema = new mongoose.Schema({
num:Number,
name: String,
size: String
})
// 增
new model({age:10,name:'save'}).save(function(err,doc){
console.log(doc);
})
// 刪
temp.remove({name:/30/},function(err){})
// 改
await model.update({age:{$gte:20}},{age:40},function(err,raw){
console.log(raw);
})
// 查
await model.find((err,doc) => {
console.log(doc)
})
15、詳細點的mangoose增刪改查
//增(new + save)
let data = await(()=>{
return new Promise((resolve, reject) => {
new model({age:10,name:'save'}).save(function(err,doc){
//[ { _id: 59720bc0d2b1125cbcd60b3f, age: 10, name: 'save', __v: 0 } ]
console.log(doc)
resolve(doc)
});
})
})()
//刪(deleteOne或者deleteMany)
let data =await model.deleteMany({name:/save/},function(err){})
//改(updateOne或者updateMany)
let data =await model.update({num:{$gte:20}},{num:40},function(err,raw){})
//查(find)
let data = await model.find(function (err,doc) {})
16、文檔判斷
$or 或關系 $nor 或關系取反 $gt 大於 $gte 大於等於 $lt 小於 $lte 小於等於 $ne 不等於 $in 在多個值范圍內 $nin 不在多個值范圍內 $all 匹配數組中多個值 $regex 正則,用於模糊查詢 $size 匹配數組大小 $maxDistance 范圍查詢,距離(基於LBS) $mod 取模運算 $near 鄰域查詢,查詢附近的位置(基於LBS) $exists 字段是否存在 $elemMatch 匹配內數組內的元素 $within 范圍查詢(基於LBS) $box 范圍查詢,矩形范圍(基於LBS) $center 范圍醒詢,圓形范圍(基於LBS) $centerSphere 范圍查詢,球形范圍(基於LBS) $slice 查詢字段集合中的元素(比如從第幾個之后,第N到第M個元素
參考鏈接:
1、mongoose基礎入門https://www.cnblogs.com/xiaohuochai/p/7215067.html?utm_source=itdadao&utm_medium=referral
2、koa初體驗https://www.jianshu.com/p/b988ce30bac3
3、koa快速入門https://www.cnblogs.com/houhanbin121456/p/8297472.html
4、使用koa離不開的十個中間件https://www.jianshu.com/p/c1e0ca3f9764
