1. 程式人生 > >nodejs學習整理(四)

nodejs學習整理(四)

3.HTTP模組

1.HTTP協議 (1)通用頭資訊 (2)響應頭資訊 (3)請求頭資訊 (4)請求主體 2.http模組 (1)模擬客戶端瀏覽器 http.get(url,callback);callback引數中的res為伺服器端相應的物件 res.on(‘data’,(buf)=>{});使用data時間獲取資料

const http=require('http');
http.get('http://www.baidu.com/',(res)=>{
	console.log(res.statusCode);
	res.on('data',(buf)=>{
		console.log(buf.toString());
	});
});

(2)建立web伺服器 var server=createrServer(); server.listen(); server.on(‘request’,(req,res)=>{});

req.url/method/headers res.write()/writeHead(302,{});/end();

const http=require('http');
var server=http.createServer();
server.listen(3000,()=>{
	console.log('success');
});

server.on('request',(req,res)=>{
	console.log('youyigeqingqiu');
    console.log(req.url);
	console.log(req.method);
	console.log(req.headers);

	res.writeHead(302,{
		Location:'http://www.baidu.com',
			'Content-Type':'text/html;charset=utf8'
	});
	res.end();
});
var server=http.createServer();
server.listen(3000);
server.on('request',(req,res)=>{
	var url=req.url;
	switch(url)
	{
		case '/login':res.write(please login');break;
		case '/student':res.writeHead(302,{
			Location:'http://www.codeboy.com'
		});break;
		case '/':res.writeHead(302,{
			Location:'http://127.0.0.1:3000/login'
		});break;
		default :res.write('404 NOT FOUND');
	}
	res.end();
});