一、使用node搭建一个服务器
const http = require('http');
// 创建一个web服务器
const server = http.createServer((req, res) => {
// request对象中封装了客户端给我们服务器传递过来的所有信息
console.log(req.url);
console.log(req.method);
console.log(req.headers);
res.end("Hello Server");
});
// 启动服务器,并且制定端口号和主机
server.listen(8888, '0.0.0.0', () => {
console.log("服务器启动成功~");
});
request请求对象
const http = require('http');
const url = require('url');
const qs = require('querystring');
// 创建一个web服务器
const server = http.createServer((req, res) => {
// /login?username=why&password=123
const { pathname, query } = url.parse(req.url);
if (pathname === '/login') {
console.log(query);
const { username, password } = qs.parse(query);
console.log(username, password);
res.end("请求结果~");
}
});
// 启动服务器,并且制定端口号和主机
server.listen(8888, '0.0.0.0', () => {
console.log("服务器启动成功~");
});
methods请求方式
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const { pathname } = url.parse(req.url);
if (pathname === '/login') {
if (req.method === 'POST') {
// 拿到body中的数据
req.setEncoding('utf-8');
// req.on('data') 这是一个监听事件 来获取body携带的数据
req.on('data', (data) => {
const {username, password} = JSON.parse(data);
console.log(username, password);
});
// 结束事件
req.on('end',() => {
console.log('传输完成')
})
res.end("Hello World");
}else {
res.end('end')
}
}
});
server.listen(8888, '0.0.0.0', () => {
console.log("服务器启动成功~");
});
设置响应状态码
const http = require('http');
// 创建一个web服务器
const server = http.createServer((req, res) => {
// 设置状态码
// 方式一: 直接给属性赋值
res.statusCode = 400;
// 方式二: 和Head一起设置
// res.writeHead(503)
// 响应结果
res.write("响应结果一");
res.end("Hello World");
});
// 启动服务器,并且制定端口号和主机
server.listen(8888, '0.0.0.0', () => {
console.log("服务器启动成功~");
});
http 原生上传文件的示例
const http = require('http');
const fs = require('fs');
const qs = require('querystring');
const server = http.createServer((req, res) => {
if (req.url === '/upload') {
if (req.method === 'POST') {
req.setEncoding('binary');
let body = '';
const totalBoundary = req.headers['content-type'].split(';')[1];
const boundary = totalBoundary.split('=')[1];
req.on('data', (data) => {
body += data;
});
req.on('end', () => {
// 整个过程需要过滤掉 上传时候的描述信息
console.log(body);
// 处理body
// 1.获取image/png的位置
const payload = qs.parse(body, "\r\n", ": ");
const type = payload["Content-Type"];
// 2.开始在image/png的位置进行截取
const typeIndex = body.indexOf(type);
const typeLength = type.length;
let imageData = body.substring(typeIndex + typeLength);
// 3.将中间的两个空格去掉
imageData = imageData.replace(/^\s\s*/, '');
// 4.将最后的boundary去掉
imageData = imageData.substring(0, imageData.indexOf(`--${boundary}--`));
fs.writeFile(`./${new Date().getMinutes()}${new Date().getSeconds()}foo.png`, imageData, 'binary', (err) => {
res.end("文件上传成功~");
})
})
}
}
});
server.listen(8000, () => {
console.log("文件上传服务器开启成功~");
})