Node慕课网学习笔记(二)

1.3 定义一个get路由
  • 当 url 后带参数时,运用 url.split(’?’)[0] 方法把ur和参数分隔开。

  • req.method 方法判断使用的是 post 请求还是 get 请求。

const http = require('http');

const server = http.createServer((req, res) => {
  const url = req.url
  const path = url.split('?')[0] //  /api/list?a=10
  const method = req.method

  // 定义路由:模拟获取留言板列表
  if (path === '/api/list' && method === 'GET') {
    res.end('this is list router')
  }

  // 定义路由:模拟创建留言
  if (path === 'api/create' && method === 'POST') {
    res.end('this is create router')
  }

  res.end('404')
})
server.listen(3000) //可以监听http请求
console.log('http请求已经被监听,3000端口');
1.4 querystring 的使用
  1. 什么是querystring?

    • url 问号?后面的都是 querystring (也叫 url 参数)
    • & 分割,key = value 形式,可继续扩展
  2. 如何利用 quetystring 实现动态网页?

    • 服务端拿到 querystring
    • 根据不同的 querystring ,返回不同的内容
  3. 使用 querystring

      const queryStr = url.split('?')[1]   // a=100&b=200
      // 解析 querystring
      const query = {}
      queryStr && queryStr.split('&').forEach(item => {
        // item 即 a=100 形式
        const key = item.split('=')[0]  // 'a'
        const val = item.split('=')[1]  // '100'
        query[key] = val  // { a: '100', b: '200' }
    

    queryStr && queryStr.split(’&’).forEach 形式,是为了防止 favicon.ico 的干扰

  4. 使用 querystring (简易方法)

    • 加入:

      const querystring = require('querystring')

      const query = querystring.parse(queryStr)

      ​ 跟上述返回结果相同

1.5 res 返回数据
  1. 返回 json 格式:
// 定义路由:模拟获取留言板列表
  if (path === '/api/list' && method === 'GET') {
    // 返回结果
    const result = {
        errno: 0,
        data: [
          { user: '张三', content: '留言1' },
          { user: '李四', content: '留言2' },
        ]
      }
    res.writeHead('200', { 'Content-type': 'application/json' })
    res.end( JSON.stringify(result) )   // res.end() 中只能是字符串
  }

  // 定义路由:模拟创建留言
  if (path === 'api/create' && method === 'POST') {
    const result = {
      errno: 0,
      message: '创建成功'
    }
    res.writeHead(200, { 'Content-type': 'application/json' })
    res.end( JSON.stringify(result) )
  }
  res.writeHead('404', { 'Content-type': 'text/plain' })
  res.end('404 Not Found')
  • res.end()方法中只能传入字符串,所以用 JSON.stringify() 方法把对象转换成字符串
  • 200 和 404 是状态码
  • res.writeHead(200, { ‘Content-type’: ‘application/json’ }) 改变状态码和文本类型
  1. 返回 html 格式:

    res.writeHead(404, { 'Content-type': 'text/html' })
        res.end(`
            <!DOCTYPE html>
            <html>
                <head>
                    <title>404</title>
                </head>
                <body>
                    <h1>404 Not Found</h1>
                </body>
            </html>
        `)
    

    浏览器会根据 Content-type 识别出 html 格式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值