node.js模块系统:
1、定义模板:
module 批量导出
module.exports = {
a: 12, b: 5
}
exports
exports.a = 12;
exports.b = 5;
require
每个文件都是一个模块
创建一个package.json文件:
npm init -y
当部署项目的时候,可以通过npm i来把需要的包都安装到本地项目内的node_modules里,不然文件太大copy费时
yarn:包管理工具
npm i yarn -g 用npm全局安装yarn
yarn add xxx 用来安装
bower-----前端包管理
npm i bower -g
bower i xxx
node 系统包:
1、assert - 断言
assert(条件, 消息);
如果条件成立,则没有消息反馈,只有不成立才会返回错误提示;
例如:assert(5<3, 'aaa');
assert.deepEqual(变量,预期值,msg); 相当于==
assert.deepStrictEqual(); 相当于===
2、path - 路径
const path = require('path');
let str = '/root/a/b/1.txt';
path.dirname(str); //获取路径
path.extname(str); //获取文件扩展名
path.basename(str); //获取文件名
path.resolve(); //获取当前路径
3、url - 网址
str = 'http://www.bing.com/a/b/1.html?a=12&b=5';
url.parse(str, true);
4、querystring - 请求数据
querystring.parse("a=12&b=9&c=22");
querystring.stringify({a: 12, b: 9, c: 'blue'});
5、net 网络通信
OSI七层参考模型:
物理层 > 数据链路层 > 网络层(IP) > 传输层(TCP) > 会话层 > 表现层 > 应用层(HTTP)
multiparty: 解决上传文件的模块
cnpm i multiparty -D
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="http://localhost:8080/aaa" method="post" enctype="multipart/form-data">
用户:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="file" name="f1">
<input type="submit" value="提交">
</form>
</body>
</html>
const http = require('http');
const multiparty = require('multiparty');http.createServer((req, res)=>{
let form = new multiparty.Form({
uploadDir: './upload'
});
form.parse(req);
form.on('field', (name, value)=>{
console.log('字段:', name, value);
});
form.on('file', (name, file)=>{
console.log('文件:', name, file);
});
form.on('close', ()=>{
console.log('表单解析完成');
});
}).listen(8080);
一、数据通信:
ajax、跨域
fetch
ajax2.0 -> FormData
webSocket
二、数据库
三、框架
原生ajax:
window.onload = function(){
let oBtn = document.getElementById('btn1');
oBtn.onclick = function(){
let ajax = new XMLHttpRequest();
ajax.open('GET', 'http://localhost:8080/a', true);
ajax.send();
ajax.onreadystatechange = function(){
//0-4 0代表初始化,1代表已连接, 2代表已发送,3代表响应的头已返回,4代表接收
if(ajax.readyState == 4){
if(ajax.status >= 200 && ajax.status < 300 || ajax.status == 304){
alert('成功');
//alert(ajax.responseText);let json = JSON.parse(ajax.responseText);
console.log(json);
}else{
alert('失败');
}
}
}
}
};
const http = require('http');
http.createServer((req, res)=>{
res.setHeader('access-control-allow-origin', '*'); //解决跨域问题
res.write('{"a": 12, "b": "blue"}');
res.end();
}).listen(8080);
const http = require('http');
let allowOrigin = {
'http://localhost' : true,
'http://aaa.com' : true,
'http://127.0.0.1:8020' : true
}http.createServer((req, res)=>{
let {origin} = req.headers;
if(allowOrigin[origin]){
res.setHeader('access-control-allow-origin', '*');
}
res.write('{"a": 12, "b": "blue"}');
res.end();
}).listen(8080);
ajax如何跨域 --- origin、access-control-allow-origin