NodeJs实现服务器配置开发

动态网站开发

const http = require('http');
const path = require('path');
const fs = require('fs');
const querystring = require('querystring');
const scoreData = require('./score.json');
http.createServcer((req,res)=>{
	//查询成绩的入口地址 /query
	if(req.url.startsWith('/query') && req.method == 'GET'){
		fs.readFile(path.join(__dirname, 'view', 'index.tpl'), 'utf8', (err, content) =>{
			if(err){
				res.writeHead(500, {
					'Content-Type' : 'text/plain;charset=utf-8'
				});
				res.end('服务器错误,请联系管理员');
			}
			res.end(content);
		});
	}
	//获取成绩结果  /score
	else if(req.url.startsWith('/score') && req.method == 'POST'){
		let pdata = '';
		req.on('data', (chunk) =>{
			pdata += chunk;
		});
		req.on('end', ()=>{
			let obj = querystring.parse(pdata);//获取前台传入的参数
			let result = scoreData[obj.code];
			fs.readFile(path.join(__dirname, 'view', 'result.tpl'), 'utf8', (err, content) =>{
				if(err){
					res.writeHead(500, {
						'Content-Type' : 'text/plain;charset=utf-8'
					});
					res.end('服务器错误,请联系管理员');
				}
				//返回内容之前要进行数据渲染
				content = content.replace("$$chinese$$", result.chinese);
				content = content.replace("$$math$$", result.math);
				res.end(content);
			});
		});
	}
	
}).listen(3000), ()=>{
	console.log('running.........');
});

index.tpl

<form action="http://localhost:8080/score">
	请输入考号: <input type="text" name="code" />
	<input type="submit" value="查询" />
</form>

result.tpl

<div>
	<ul>
		<li>语文:$$chinese$$</li>
		<li>语文:$$math$$</li>
	</ul>
</div>

scores.json

{
	'no123' :{
		"chinese" : "100",
		"math" : "140"
	},
	'no124' :{
		"chinese" : "100",
		"math" : "140"
	},
	'no125' :{
		"chinese" : "100",
		"math" : "140"
	},
}	

静态服务器功能HTTP模块

const http = require('http');
//创建服务器实例对象
let server = http.createServer();
//绑定请求对象
server.on('request', (req, res) =>{
	res.end('hello');
});
//服务器端口 监听端口
server.listen(3000);

//简写方式
http.createServer((req, res) =>{
	res.end('OK');
}).listen(3000, [ip], ()=>{
	console.log('running .....');
});

请求路径分发

const http = require('http');
http.createServer((req, res) =>{
	//获取请求的路径
	res.end(req.url);
	if(req.url.startsWith('/index')){
		//向客户端响应内容 可以写多次
		res.write('hello');
		res.write('hi');
		//用来完成响应,只能执行一次
		res.end('index');
		//res.end();
	}else if(req.url.startsWith('/about')){
		res.end('about');
	}else{
		res.end('no content');
	}
}).listen(3000, [ip], ()=>{
	console.log('running .....');
});	

响应完整的页面信息

index.html

<div>欢迎访问</div>

about.html

<div>关于我们</div>

list.html

<div>列表页面</div>
const http = require('http');
const path = require('path');
const fs = require('fs');
//根据路径读取文件
let readFile = (url, res) =>{
	fs.readFile(path.join(__dirname, 'www', url), 'utf8', (err, fileContent) =>{
		if(err){
			res.end("server error");
		}else{
			res.end(fileContent);
		}
	});
};
http.createServer((req, res) =>{
	//处理文件的分发
	if(req.url.startsWith('/index')){
		readFile('index.html', res);
	}else if(req.url.startsWith('/about')){
		readFile('about.html', res);
	}else if(req.url.startsWith('/list')){
		readFile('list.html', res);
	}else{
		//需要设置编码,否则中文显示乱码
		res.writeHead(200, {
			'Content-Type': 'text/plain;charset=utf8'
		});
		res.end('no content');
	}
}).listen(3000, [ip], ()=>{
	console.log('running .....');
});	

优化上面JS代码

//图片也没有问题	
const http = require('http');
const path = require('path');
const fs = require('fs');
const mime = require('./mime.json');
http.createServer((req, res) =>{
	fs.readFile(path.join(root, req.url),(err, fileContent) =>{
		if(err){
			res.writeHead(404, {
				'Content-Type': 'text/plain;charset=utf8'
			});
			res.end('server error');
		}else{
			//根据不同的文件扩展名,设置不同的响应头
			let dtype = 'text/html';
			let ext = path.extname(req.url);
			if(mime[ext]){
				dtype = mime[ext];
			}
			//如果显示的是文本信息,那么设置编码
			if(dtype.startsWith('text')){
				dtype += ';charset=utf8';
			}
			res.writeHead(200,{
				'Content-Type': dtype
			});
			res.end(fileContent);
		}
	});
}).listen(3000, [ip], ()=>{
	console.log('running .....');
});	

分离JS文件

staticServer.js

const path = require('path');
const fs = require('fs');
const mime = require('./mime.json');
exports.staticServer = (req, res, root) =>{
	fs.readFile(path.join(root, req.url),(err, fileContent) =>{
		if(err){
			res.writeHead(404, {
				'Content-Type': 'text/plain;charset=utf8'
			});
			res.end('server error');
		}else{
			//根据不同的文件扩展名,设置不同的响应头
			let dtype = 'text/html';
			let ext = path.extname(req.url);
			if(mime[ext]){
				dtype = mime[ext];
			}
			//如果显示的是文本信息,那么设置编码
			if(dtype.startsWith('text')){
				dtype += ';charset=utf8';
			}
			res.writeHead(200,{
				'Content-Type': dtype
			});
			res.end(fileContent);
		}
	});
}

test.js

const ss = require('staticServer.js');
const http = require('http');
const path = require('path');
http.createServer((req, res) => {
	ss.staticServer(req, res, path.join(__dirname, 'www'));
}).listen(3000, ()=>{
	console.log('running');
});

参数传递与获取

Get参数获取

//url.parse()方法演示
const url = require('url');
let str = 'http://www.baidu.com/abc?flag=sadf&keyword=java';
//第二个参数方便获取传递的参数
let ret = url.parse(str [,true]);
console.log(ret);
console.log(ret.query);//获取参数

//url.format()方法演示
let obj = {
	  protocol: 'http:',
	  slashes: true,
	  auth: null,
	  host: 'www.baidu.com',
	  port: null,
	  hostname: 'www.baidu.com',
	  hash: null,
	  search: '?flag=sadf&keyword=java',
	  query: [Object: null prototype] { flag: 'sadf', keyword: 'java' },
	  pathname: '/abc',
	  path: '/abc?flag=sadf&keyword=java',
	  href: 'http://www.baidu.com/abc?flag=sadf&keyword=java' 
}
let ret1 = url.format(obj);
console.log(ret1);

//测试get方式获取参数
const http = require('http');
const path = require('path');
const url = require('url');
http.createServer((req, res) =>{
	let obj = url.parse(req.url, true);
	res.end(obj.query.usename + '=============='+ obj.query.password);
}).listen(3000, ()=>{
	console.log('running...');
});

Post方式获取参数

//parse()方法将字符串转换成对象
const querystring = require('querystring');
let param = 'username=lisi&password=123';
let obj = querystring.parse(param);
console.log(obj);
console.log(obj.username);

//stringify将对象转换成字符串
let obj1 = {
	'flag'; '124',
	abc : 'hello'
} 	
let str1 = querystring.stringify(obj1);
console.log(str1);

//测试服务器POST传递参数处理
const querystring = require('querystring');
const http = require('http');
http.createServer((req, res) =>{
	if(req.url.startsWith('/login')){
		let pdata = '';
		req.on('data', (chunk) =>{
			pdata += chunk;
		});
		req.on('end', ()=>{
			console.log(pdata);
			let obj = querystring.parse(pdata);
			res.end(obj.username +'---'+ obj.password);
		});
	}
}).listen(3000, ()=>{
	console.log('running......');
});

以上是针对Http模块以及URL模块基本使用的总结。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值