[TOC]
>[success] # 處理get請求
* **get請求**,即 **客戶端** 要向 **server 端** 獲取數據,如查詢博客列表,**查詢都用get**
* 通過 **querystring** 來傳遞數據,如 **a.html?a=100&b=200**
* **瀏覽器輸入url手動在后面拼接參數,直接訪問,就發送get請求**
>[success] ## get請求和 querystring
1. 首先初始化項目,執行 **npm init -y** ,然后會生成初始化的 **package.json** 文件,把里面的 **main** 入口配置文件名改成 **app.js**
**package.json**
~~~
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
~~~
2. 創建 **app.js** ,然后寫處理 **get請求** 的邏輯
**app.js**
~~~
// 1. 引入node自帶的http模塊
const http = require('http')
// 2. 引入querystring模塊
const querystring = require('querystring')
// 3. 通過http創建服務
const server = http.createServer((req, res) => {
console.log(req.method) // GET
// 4. 獲取請求的完整 url ,http://127.0.0.1:8000/?a=100&b=200
const url = req.url
// 5. 把 a=100&b=200 解析成對象 {"a":"100","b":"200"}
req.query = querystring.parse(url.split('?')[1])
// 6. 把參數轉換成json字符串返回
res.end(JSON.stringify(req.query))
})
// 7. 監聽8000端口
server.listen(8000)
~~~
在編輯器終端執行 **node app.js** 啟動該文件的服務,然后在瀏覽器輸入 **localhost:8000或127.0.0.1** ,因為這里的 **http** 服務是 **8000** 端口,此時能看到頁面有一個空對象

在 **url** 后面拼接參數,就可以看到拼接的參數被后臺成功返回,并且展示到了頁面上

這樣就成功的解析到了 **get** 請求的參數。
- NodeJS基礎
- 什么是NodeJS
- npm
- Node.js+Express+Koa2+開發Web Server博客
- 下載和安裝node
- nodejs和js的區別
- commonjs-演示
- nodejs如何debugger
- server端與前端的區別
- 項目需求分析
- 開發接口(不使用任何框架)
- http-概述
- 處理get請求
- 處理post請求
- 處理http請求的綜合示例
- 搭建開發環境
- 初始化并且開發路由
- 開發博客項目之數據存儲
- MySql介紹
- 數據庫操作(創建和增、刪、查)
- Nodejs 操作 Mysql
- Nodejs 鏈接 mysql 做成工具
- API 對接 MySQL
- 開發博客項目之登陸
- cookie-介紹
- cookie用于登錄驗證
- cookie做限制