1.用法示例
通過下面的用法,可以瞭解http用法。
'use strict';
let http = require('http');
let url = require('url');
let querystring = require('querystring')
/**
* @description 創建服務器
*/
function createServer() {
//注意:當我們在服務器訪問網頁時,我們的服務器可能會輸出兩次“get request”。那是因爲大部分瀏覽器都會在你訪問 http://localhost:8888/時嘗試讀取 http://localhost:8888/favicon.ico )
let server = http.createServer((request, response) => {
//解析請求路徑
let urlObj = url.parse(request.url)
console.log(urlObj)
//解析請求參數
let queryObj = querystring.parse(urlObj.query)
console.log(queryObj)
//路由處理
if (urlObj.pathname === '/testRequest') {
//發送post請求
postTest(response);
} else if (urlObj.pathname === '/testPost') {
//發送post請求, 接收並處理post data
let jsonData = '';
request.on("data", function(data) {
jsonData += data
console.log('接受數據中。。。');
});
request.on("end", function() {
console.log('接受完成!');
console.log(querystring.parse(jsonData));
})
} else {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('hello nodeJs!')
response.end();
}
})
server.listen(8888);
console.log('Server is running at http://127.0.0.1:8888/');
}
function postTest(response) {
let postData = querystring.stringify({
'msg': 'Hello World!'
})
//發送post請求localhost:8888/test並帶上參數postData
let options = {
hostname: 'localhost',
port: 8888,
path: '/test',
method: 'POST',
headers: {
'Content-Type': '"text/plain',
'Content-Length': postData.length
}
};
let req = http.request(options);
req.write(postData);
req.end()
}
module.exports = {
createServer: createServer
}