Nodejs資料之web服務器

◆ 創建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('網站服務器啓動成功');
發佈了293 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章