目錄
nodejs是什么
使用nodejs創(chuàng)建一個(gè)服務(wù)器(接口)
nodejs的模塊系統(tǒng)
nodejs文件系統(tǒng)
路徑模塊path
npm相關(guān)
-
nodejs的koa框架
- 創(chuàng)建第一個(gè)koa服務(wù)
-
koa路由
- 靜態(tài)服務(wù)
跨域
ql框架
(一) nodejs是什么
- 運(yùn)行在服務(wù)器的JavaScript代碼
- 可以寫服務(wù)接口
- nodejs可以操作本地文件
(二) 使用nodejs創(chuàng)建一個(gè)服務(wù)器(接口)
app.js 代碼如下
var http = require('http');
/或去http的createServer方法 傳參傳進(jìn)一個(gè)函數(shù)這個(gè)函數(shù)分別傳進(jìn)請求數(shù)據(jù)(request)和發(fā)送數(shù)據(jù)(response)
http.createServer(function (request, response) {
// 發(fā)送 HTTP 頭部
// HTTP 狀態(tài)值: 200 : OK
// 內(nèi)容類型: text/plain
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello World');
}).listen(8888);
// 終端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');
運(yùn)行 nodejs app.js
啟動(dòng)服務(wù)
(三) nodejs的模塊系統(tǒng)
導(dǎo)出模塊和導(dǎo)入模塊
導(dǎo)出用module.exports
導(dǎo)入用require
例子1: 導(dǎo)出一個(gè)數(shù)組
// m1.js
module.exports = [];
// index1.js
let list = require('./m1');
console.log(list);
運(yùn)行index1.js
node index1.js
例子2: 導(dǎo)出一個(gè)函數(shù)
// m2.js
function add(a,b) {
return a+b;
}
module.exports = add;
// index2.js
let add = require('./m2');
let sum = add(100, 200);
console.log('sum', sum);
運(yùn)行index2.js
node index2.js
例子3: 導(dǎo)出一個(gè)對(duì)象
// m3.js
var username = '張三';
var age = 100;
function say() {
console.log('我是' + username);
}
module.exports = {
username,
age,
say
}
// index3.js
let obj = require('./m3');
console.log('用戶名', obj.username);
obj.say();
運(yùn)行index3.js
node index3.js
(四) nodejs文件系統(tǒng)
- 讀取文件
// 例子1 異步讀取
新建input.txt文件,內(nèi)容隨意
?
// index1.js
var fs = require("fs");
?
console.log(1);
// 異步讀取
fs.readFile('input.txt', function (err, data) {
console.log(2);
if (err) {
return console.error(err);
}
console.log("異步讀取: " + data.toString());
});
console.log(3);
// 例子2
var fs = require('fs');
// 同步讀取
var data = fs.readFileSync('input.txt');
console.log("同步讀取: " + data.toString());
console.log("程序執(zhí)行完畢丹禀。");
-
寫入文件
// 例子1 異步寫入 var fs = require("fs"); ? console.log("準(zhǔn)備寫入文件"); var str = '困難是我們的食物'; ? fs.writeFile('data.txt', str, function (err) { /讀取文件進(jìn)行判斷锭沟,如果是錯(cuò)誤的時(shí)候鳍置,那么if里面的代碼 if (err) { return console.error(err); } console.log('文件寫入成功') });
// 例子2 同步讀取
var fs = require("fs");
var str = '困難是我們的食物';
fs.writeFileSync2('data.txt', str);
console.log('文件寫入成功');
// 添加trycatch可以捕捉寫入過程中發(fā)生的錯(cuò)誤
try {
fs.writeFileSync2('data.txt', str);
console.log('文件寫入成功');
} catch (error) {
console.log('錯(cuò)誤信息', error);
}
(五) 路徑模塊path
-
path.join() 路徑連接,能夠起到兼容作用,以下兩個(gè)打印的結(jié)果都是 '\nodejs\dist';
let path = require('path'); let str1 = path.join('/nodejs','dist'); console.log(str1); let str2 = path.join('\\nodejs','dist'); console.log(str2);
-
path.resolve() 把路徑變成絕對(duì)路徑
let path = require('path') let str1 = path.resolve('nodejs', 'dist'); console.log('str1', str1); let str2 = path.join('\\nodejs', 'dist'); console.log('str2', str2);
-
__dirname
let path = require('path'); console.log(__dirname); // 顯示當(dāng)前目錄 let str = path.resolve(__dirname, 'dist'); console.log('str', str);
(六) npm相關(guān)
目錄
-
npm是什么
npm是nodejs模塊(包)管理工具
模塊存放網(wǎng)站 https://www.npmjs.com/
-
npm常用操作
- 初始化package.json
npm init // 或 npm init -y
- 安裝一個(gè)nodejs模塊
npm i xxx // 記錄在 dependencies
npm i xxx -S // 同上
npm i xxx --save-dev // 記錄devDependencies
npm i xxx -D // 同上
?npm i xxx -g // 全局
npm i // 當(dāng)我們把node_modules刪掉,使用npm i 可以把所有依賴都安裝回來
- 更新nodejs模塊
npm update xxx
- 刪除nodejs模塊
npm uninstall xxx
- 運(yùn)行指令
npm run xxx
(七) Class類
-
定義一個(gè)"人類"
class People {
//constructor構(gòu)造器 構(gòu)造函數(shù)
constructor(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
?
// 定義一個(gè)方法
writeCode() {
console.log(this.name + " " + this.age + " " + this.sex)
}
say() {
console.log("他的名字是" + " " + this.name)
}
}
let p = new People("阿華", 21, "男")
console.log(p)
p.say()
p.writeCode()
class Man extends People {
constructor(name, age, sex) {
super(name, age, sex)
this.have = true
}
}
/*let man = new Man('靚仔', 18 + '歲',"男")
man.say()
man.writeCode()
console.log(man)*/
-
繼承
// 男人類繼承人類
class Man extends Person {
constructor(name, age, sex) {
// 調(diào)用父類的構(gòu)造器(構(gòu)造方法)
super(name, age, sex);
this.haveBeard = true;
}
}
?
let man = new Man('陳燦', 18, '男');
console.log(man);
man.say();
man.writeCode();
(八) nodejs的koa框架
文檔地址: https://koa.bootcss.com/
https://www.npmjs.com/package/koa
-
koa框架以及其他的nodejs框架
express.js框架和koa.js框架是同一個(gè)團(tuán)隊(duì)做的
egg.js 阿里
hapi.js
-
hello world
初始化package.json
安裝
npm i koa
- 創(chuàng)建app.js,代碼如下
// 導(dǎo)入koa框架 const Koa = require('koa'); // 創(chuàng)建實(shí)例 const app = new Koa(); // ctx上下文,use里的函數(shù)成為中間件(插件) app.use(ctx => { // ctx.body用來給前端返回?cái)?shù)據(jù) ctx.body = 'Hello Koa'; }); app.listen(3000);
-
啟動(dòng)服務(wù)
node app.js
-
服務(wù)器自動(dòng)重啟
-
全局安裝nodemon模塊
npm i nodemon -g
-
啟動(dòng)項(xiàng)目的時(shí)候,使用
nodemon app.js 代替 node app.js
-
-
koa路由
-
安裝
npm install koa-router
-
app.js的代碼如下
const Koa = require('koa'); const Router = require('koa-router'); ? const app = new Koa(); const router = new Router(); ? // 增加 router.all('/city/add', (ctx, next) => { ctx.body = '添加城市'; }); router.all('/city/getList', (ctx, next) => { ctx.body = '城市列表'; }); router.all('/city/update', (ctx, next) => { ctx.body = '更新城市'; }); router.all('/city/del', (ctx, next) => { ctx.body = '刪除城市'; }); // 使用之后路由才生效 app.use(router.routes()); ? app.listen(3000, () => { console.log('服務(wù)已啟動(dòng),在 http://localhost:3000') });
-
運(yùn)行
nodemon app.js
-
-
跨域
在app.js里添加下面這句話,即可進(jìn)行簡單的跨域設(shè)置
app.use((ctx, next) => { ctx.set("Access-Control-Allow-Origin", "*"); ctx.set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS"); // 請求頭設(shè)置 ctx.set( "Access-Control-Allow-Headers", `Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild,x-token,sessionToken,token` ); if (ctx.method == "OPTIONS") { ctx.body = 200; } else { next(); } })
-
中間件
-
中間件從上到下執(zhí)行
- 需要調(diào)用next() 去執(zhí)行下一個(gè)中間件
// 中間件(插件) app.use((ctx, next) => { ctx.username = 'lao hu'; console.log(1); next(); }) app.use((ctx, next) => { console.log(2); console.log(ctx.username); next(); }) app.use((ctx, next) => { console.log(3); next(); })
7. 獲取請求參數(shù)
-
獲取get請求參數(shù)
// 前端get請求傳過來的參數(shù),放在ctx.request.query對(duì)象內(nèi) (ctx, next) => { // let name = ctx.request.query.name; // let isHot = ctx.request.query.isHot; // 或者使用解構(gòu)的方式來取 let {name,isHot} = ctx.request.query; }
- 獲取post請求參數(shù)
-
安裝koa-body
npm i koa-body
-
在app.js添加以下代碼
const koaBody = require('koa-body'); app.use(koaBody()); // 請放在跨域的代碼前
-
獲取post請求參數(shù)
// 前端post請求傳過來的參數(shù),全部放入ctx.request.body對(duì)象里 let { pageNum } = ctx.request.body; console.log('pageNum', pageNum);
-
為了方便獲取參數(shù),可以自定義一個(gè)中間件
// 兼容get和post請求的中間件 app.use((ctx, next) => { ctx.params = { ...ctx.request.query, ...ctx.request.body } next(); })