nodejs,,一些基本操作--server。js


1.解決中文亂碼問題:

const http = require('http')

const server = http.createServer((req, res) => {
    // 設置字符編碼 - 設置文本的解析形式
    // 200 表示本次請求是成功的
    // text/html     ----   解析標簽輸出
    // text/plain    ----   轉義標簽輸出   ----  原樣輸出
    // nodejs服務器 默認是 text/html
    res.writeHead(200, {
        'Content-Type': 'text/plain;charset=utf-8'
    })
    res.write('<h1>hello world</h1>')
    res.write('<h2>您好</h2>') // 如果出現中文字符,默認會亂碼   ---- 設定字符編碼
    res.end()
}) 

server.listen(3000)

console.log('your server is runing at http://localhost:3000')

// ???? 打開控制台 -》 NETWORK,刷新頁面,發現有2個請求  --- 要的是一個請求 ---- 過濾不需要的請求2.

2.解析網址(自己設置的網址)

// http
// 解析網址   url
/**
 * 完整的URL地址的解析字段
┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                              href                                              │
├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
│ protocol │  │        auth         │          host          │           path            │ hash  │
│ 協議      │  │                     ├─────────────────┬──────┼──────────┬────────────────┤       │
│          │  │                     │    hostname     │ port │ pathname │     search     │       │
│          │  │                     │     域名         │ 端口  │   路由   ├─┬──────────────┤       │
│          │  │                     │                 │      │          │ │    query     │       │
"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash "
│          │  │          │          │    hostname     │ port │          │                │       │
│          │  │          │          ├─────────────────┴──────┤          │    參數         │ 哈希值│
│ protocol │  │ username │ password │          host          │          │                │       │
├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       │
│   origin    │                     │         origin         │ pathname │     search     │ hash  │
├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
│                                              href                                              │
└────────────────────────────────────────────────────────────────────────────────────────────────┘
 * 
 */
const url = require('url')

const urlStr = "http://localhost:3000/login?username=wudaxun&password=123456"

// url.parse(urlStr[, boolean]) --- 將字符串類型的網址轉換成對象

const obj = url.parse(urlStr,true)

// console.log(obj)

/**
 * Url {
  protocol: 'http:', // 協議
  slashes: true,
  auth: null, // 作者
  host: 'localhost:3000', // 域名 + 端口
  port: '3000', // 端口
  hostname: 'localhost', // 域名
  hash: null, // 哈希值
  search: '?username=wudaxun&password=123456', // ? + 參數
  query: 'username=wudaxun&password=123456', // 字符串類型的參數
  pathname: '/login', // 路由
  path: '/login?username=wudaxun&password=123456', // 路由 + ? + 參數
  href: 'http://localhost:3000/login?username=wudaxun&password=123456' // 完整的地址
}
 */

 console.log(obj.query)  // username=wudaxun&password=123456
 console.log(obj.query.username) //wudaxun
 console.log(obj.query.password) //123456

2.1.過濾圖標設置圖標

 

/**
 * 過濾圖標 、設置路由
 */
const http = require('http');
const url = require('url'); // 獲取前端請求的信息 ---  url.parse() 字符串的url轉成對象

const server = http.createServer((req, res) => {
    if (req.url !== '/favicon.ico') { // 過濾圖標的請求
    res.writeHead(200, {
        'Content-Type': 'text/html;charset=utf-8'
    })

    const urlObj = url.parse(req.url, true) // true 將參數類型的字符串轉成對象

    // // write函數不能輸出對象,可以輸出字符串 ---- 對象轉字符串
    // res.write(JSON.stringify(urlObj))

    // 拿路由
    // const pathname = urlObj.pathname
    const { pathname } = urlObj;

    res.write('<h1>您好,世界!</h1>' + pathname);

    res.end();
}
});

server.listen(3000);

console.log('your server is running at http://localhost:3000');

// querystring  username=wudaxun&password=123456&sex=1&age=18 轉成 對象

 

 

 

 

3.querystrng將參數類型的字符串轉換成對象類型

/**
 * querystring
 *      將參數類型的字符串轉換成對象類型
 * 
 *  username=wudaxun&password=123456  
 * 
 *      ===>
 *  
 *  { username: wudaxun, password: 123456 }
 */
const querystring = require('querystring')

const queryStr = 'username=wudaxun&password=123456&age=18'

// querystring.parse(queryStr)  *---- 將字符串類型的參數 轉換成 對象

const obj = querystring.parse(queryStr)

console.log(obj)

/***
 * {
  username: 'wudaxun',
  password: '123456',
  age: '18'
}

總結:
    實際開發過程中並不需要使用 querystring,建議使用 url.parse(str, true) url.parse()的第二個參數為true可轉對象,其原理就是 querystring.parse() */


 // ??? 已知的網頁字符串可以搞定,那么如果是用戶輸入的網址呢?

4.解析網址(服務器獲取的網址)

const http = require('http')
const url = require('url')

const server = http.createServer((req, res) => {
    if (req.url !== '/favicon.ico') {
        res.writeHead(200, {
            'Content-Type': 'text/html;charset=utf-8'
        })

        const urlStr = req.url // /login?username=wudaxun&password=123456

        const obj = url.parse(urlStr, true).query // { username: 'wudaxun', password: '123456' }

        const { username, password } = obj

        res.write(`用戶名:${username}`)
        res.write(`密碼: ${password}`)

        res.end()

    }
})

server.listen(3000)

// 登錄 注冊表單 不要使用  &  --- 丟失數據


/**
 * 如果用戶輸入  /home  那么輸出  首頁
 * 如果用戶輸入  /kind  那么輸出  分類
 * 如果用戶輸入  /cart  那么輸出  購物車
 * 如果用戶輸入  /user  那么輸出  個人中心
 */

fs(file-system)

/**
 * fs    ----  file system
 *  后端語言的標志:
 *      文件的讀寫
 */

 // 文件的讀操作
 // fs.readFile(path, 'utf-8', (err, data) => {})

 const fs = require('fs')

 fs.readFile('./01node介紹.html', 'utf-8', (err, data) => {
    if (err) {
        console.log(err)
    } else {
        console.log(data)
    }
 })
 

在服務器打開別的網頁:

const http = require('http')
const fs = require('fs')
const server = http.createServer((req, res) => {
    if (req.url !== '/favicon.ico') {
        res.writeHead(200, {
            'Content-Type': 'text/html;charset=utf-8'
        })

        fs.readFile('./12test.html', 'utf-8', (err, data) => {
            if (err) throw err // 遇到錯誤,拋出異常,代碼不再繼續執行
            res.write(data)
            res.end()
        })
    }
})

server.listen(3000)


/**
 * 如果用戶輸入  /home  那么輸出  首頁.html
 * 如果用戶輸入  /kind  那么輸出  分類.html
 * 如果用戶輸入  /cart  那么輸出  購物車.html
 * 如果用戶輸入  /user  那么輸出  個人中心.html
 */

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM