简单node服务器demo,麻雀虽小,五脏俱全
//本服务器要实现的功能如下: //1.静态资源服务器(能读取静态资源) //2.能接收get请求,并能处理参数 //3.能接收post请求,并能处理参数 const http = require('http'); const fs = require('fs'); const url = require('url'); const querystring = require('querystring'); const server = http.createServer(); server.on('request', (req, res) => { //用于存放get / post数据 let getParams = '',postParams = ''; //处理get const obj = url.parse(req.url, true); let pathname = obj.pathname; getParams = obj.query; console.log('你发送的get数据如下:',getParams) //处理post let str = ''; req.on('data',(data)=>{ str += data; }) req.on('end',()=>{ postParams = querystring.parse(str);//将字符串转换为对象 console.log('你发送的post数据如下:',postParams) }) //处理文件 if(pathname === '/'){ pathname = '/index.html' } if(pathname.indexOf('favicon') != -1){ return } let fileName = './' + pathname; fs.readFile(fileName,(err,data)=>{ if(err){ console.log(pathname) console.log(err) }else{ res.write(data) } res.end(); }) }) server.listen(8080, () => { console.log('服务器开启成功!') });
//本服务器要实现的功能如下:
//1.静态资源服务器(能读取静态资源)
//2.能接收get请求,并能处理参数
//3.能接收post请求,并能处理参数
const http = require('http');
const fs = require('fs');
const url = require('url');
const querystring = require('querystring');
const server = http.createServer();
server.on('request', (req, res) => {
//用于存放get / post数据
let getParams = '',postParams = '';
//处理get
const obj = url.parse(req.url, true);
let pathname = obj.pathname;
getParams = obj.query;
console.log('你发送的get数据如下:',getParams)
//处理post
let str = '';
req.on('data',(data)=>{
str += data;
})
req.on('end',()=>{
postParams = querystring.parse(str);//将字符串转换为对象
console.log('你发送的post数据如下:',postParams)
})
//处理文件
if(pathname === '/'){
pathname = '/index.html'
}
if(pathname.indexOf('favicon') != -1){
return
}
let fileName = './' + pathname;
fs.readFile(fileName,(err,data)=>{
if(err){
console.log(pathname)
console.log(err)
}else{
res.write(data)
}
res.end();
})
})
server.listen(8080, () => {
console.log('服务器开启成功!')
});