◆ 创建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 // 获取请求方法
});
◆ GET请求处理:
参数被放置在浏览器地址栏中,获取参数需要使用系统模块url来处理url地址
// 引入创建网站服务器的模块
const http = require('http');
// 用于处理url地址
const url = require('url');
// app对象就是网站服务器对象
const app = http.createServer();
// 当客户端有请求来的时候
app.on('request', (req, res) => {
// 获取请求方式
// req.method
// console.log(req.method);
// 获取请求地址
// req.url
// console.log(req.url);
// 获取请求报文信息
// req.headers
// console.log(req.headers['accept']);
res.writeHead(200, {
'content-type': 'text/html;charset=utf8'
});
console.log(req.url);
// 1) 要解析的url地址
// 2) 将查询参数解析成对象形式
let { query, pathname } = url.parse(req.url, true);
console.log(query.name)
console.log(query.age)
if (pathname == '/index' || pathname == '/') {
res.end('<h2>欢迎来到首页</h2>');
}else if (pathname == '/list') {
res.end('welcome to listpage');
}else {
res.end('not found');
}
if (req.method == 'POST') {
res.end('post')
} else if (req.method == 'GET') {
res.end('get')
}
// res.end('<h2>hello user</h2>');
});
// 启动监听端口
app.listen(3000);
console.log('网站服务器启动成功');
◆ POST请求处理:
参数被放置在请求体中进行传输,获取POST参数需要使用data事件和end事件。使用querystring系统模块将参数转换为对象格式
// 用于创建网站服务器的模块
const http = require('http');
// app对象就是网站服务器对象
const app = http.createServer();
// 处理请求参数模块
const querystring = require('querystring');
// 当客户端有请求来的时候
app.on('request', (req, res) => {
// post参数是通过事件的方式接受的
// data 当请求参数传递的时候触发data事件
// end 当参数传递完成的时候触发end事件
let postParams = '';
// 监听参数传输事件
req.on('data', params => {
postParams += params;
});
// 监听参数传输完毕事件
req.on('end', () => {
console.log(querystring.parse(postParams));
});
res.end('ok');
});
// 启动监听端口
app.listen(3000);
console.log('网站服务器启动成功');