nodejs,,一些基本操作--server。js 1.解决中文乱码问题: 2.解析网址(自己设置的网址) 2.1.过滤图标设置图标   3.querystrng将参数类型的字符串转换成对象类型 4.解析网址(服务器获取的网址) fs(file-system) 在服务器打开别的网页:

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
 */