创建web服务器
//引用系统模块
const http = require('http');
//创建web服务器
const app = http.createServer();
//当客户端发送请求的时候
app.on('request',(req,res) => {
//响应
res.end('<h1>hi,user</h1>');
});
//监听3000端口
app.listen(3000);
console.log('服务器已启动,监听3000端口,请访问localhost:3000');
请求报文
app.on('request',(req,res) => {
req.headers //获取请求报文
req.url //获取请求地址
req.method //获取请求方法
});
响应报文
app.on('request',(req,res) => {
res.writeHead(200,{
'Content-Type':'text/html;charset=utf8'
})
});
GET请求参数
http://localhost:3000?name=zhangsan&age=20
const http = require('http');
//导入url系统模块 用于处理url地址
const url = require('url');
const app = http.createServer();
app.on('request',(req,res) => {
//将url路径的各个部分解析出来并返回对象
//true代表将参数解析为对象格式
let (query) = url.parse(req.url,true);
console.log(query);
})
app.listen(3000);
POST请求参数
//导入系统模块querystring用于将HTTP参数转换为对象格式
const querystring = require('querystring');
app.on('request',(req,res) => {
let postData = '';
//监听参数传输时间
req.on('data',(chunk) => postData += chunk;);
//监听参数传输完毕事件
req.on('end',() => {
console.log(querystring.parse(postData));
});
});
路由
//当客户端发来请求的时候
app.on('request',(req,res) => {
//获取客户端的请求路径
let { pathname } = url.parse(req.url);
if (pathname == '/' || pathname == '/index'){
res.end('欢迎来到首页');
}else if (pathname == '/list'){
res.end('欢迎来到列表页');
}else{
res.end('抱歉,您访问的页面出游了');
}
});
Promise
let promise = new Promise((resolve,reject) => {
setTimeout(() => {
if(true){
resolve({name:'张三'})
}else{
reject('失败')
}
},2000);
});
promise.then(result => console.log(result); //{name:'张三'})
.catch(error => console.log(error); //失败了)
异步函数
const fn = async() => {};
或
async function fn () {}
async关键字
1.普通函数定义前加async关键字 普通函数编程异步函数
2.异步函数默认返回pomise对象
3.在异步函数内部使用return关键字进行结果返回 结果会被包裹的promise对象中return关键字代替了resolve方法
4.在异步函数内部使用throw关键字抛出程序异常
5.调用异步函数再链式调用then方法获取异步函数执行结果
6.调用异步函数再链式调用catch方法获取异步函数执行的错误信息
await关键字
1.await关键字只能出现在异步函数中
2.await promise await后面只能promise对象 写其他类型的API是不可以的
3.await关键字可以暂停异步函数向下执行 直到promise返回结果







网友评论