不同方式node.js构建服务器

作业解答

const fs = require('fs')
const path = require('path')
const querystring = require('querystring')
const obj = {}

fs.readFile(path.join(__dirname, './1.txt'), 'utf8', (err, dataStr) => {
  if (err) return console.log(err.message)
  const arr = dataStr.trim().split('\n')
  let newArr = []
  // console.log(arr)
  arr.forEach(item => {
    // console.log('{"' + item.replace(/ /g, '\",\"').replace(/\=/g, '\":\"') + '"}')
    // newArr.push(JSON.parse('{"' + item.replace(/ /g, '\",\"').replace(/\=/g, '\":\"') + '"}'))
    // console.log(querystring.parse(item, ' '))
    querystring.parse
 
    newArr.push(querystring.parse(item, ' '))
  })

  // console.log(newArr)
  obj.message = newArr
  
  fs.writeFile(path.join(__dirname, './3.json'), JSON.stringify(obj, null, '\t'), err => {
    if (err) return console.log(err.message)
    console.log('数据转换成功')
  })
})

querystring

  • 参数1 转换的字符串
  • 参数2 以 & 替换为
  • 参数3 以 = 替换为 引号

JSON.stringify

  • 参数1 转换的数据
  • 参数2 callback 默认为null
  • 参数3 数据的格式

node手写构建服务器

步骤

`

  1. 引入http模块
  2. 创建服务
  3. 监听前端的请求
  • req 前端请求的对象
  • res 后端的响应对象
  1. 监听端口号
  • port 端口号
  • host ip 可选 默认为 localhost
  • callback 可选
    `
const http = require('http')
const server = http.createServer()
server.on('request', (req, res) => {
  console.log('来了老弟!')
  res.end('hello node')
})
server.listen(3000, ['10.41.250.82', '127.0.0.1'], () => {
  console.log('本地服务 http://127.0.0.1:3000')
  console.log('远程服务 http://10.41.250.82:3000')
})

根据不同要求返回不同资源

const fs = require('fs')
const path = require('path')
const http = require('http')


const server = http.createServer()

server.on('request', (req, res) => {
方式一
if (req.url === '/index.html') {
     Static(req.url, res)
   }
   else if (req.url === '/about.html') {
   fs.readFile(path.join(__dirname, './views', req.url), (err, data) => {
        if (err) return console.log(err.message)
        res.end(data)
      })
 

  else if (req.url === '/1.png') {
      fs.readFile(path.join(__dirname, './views', req.url), (err, data) => {
        if (err) return console.log(err.message)
        res.end(data)
      })
   else if (req.url === '/api/post' && req.method === 'POST') {
     res.end('post')
   }
方式二
  Static(req.url, res)

})


server.listen(3000, ['10.41.250.82', '127.0.0.1'], () => {
  console.log('本地服务 http://127.0.0.1:3000')
  console.log('远程服务 http://10.41.250.82:3000')
})


function Static(url, res) {
  fs.readFile(path.join(__dirname, './views', url), (err, data) => {
    if (err) return console.log(err.message)
    res.end(data)
  })
}

express 及 artTemplate(服务器渲染)

// 1. 引入express  
const express = require('express')
const path = require('path')
const artTemplate = require('art-template')

// 2. 创建服务 
const app = express()

// 3. 监听前端的请求 
// app.get('/', (req, res) => {
//   // res.end('首页')
//   res.send('首页')
// })

app.get('/index.html', (req, res) => {
  // res.end('首页')
  // res.send('首页')
  // sendFile 只适合返回单个静态资源
  // res.sendFile(path.join(__dirname, './views/index.html'))

  var obj = {
    name: 'fly',
    age: 18,
    hobby: ['吃饭', '睡觉', '上号']
  }
  const html = artTemplate(path.join(__dirname, './views/index.html'), obj)
  // console.log(html)
  res.send(html)
})
// app.get('/about.html', (req, res) => {
//   // res.end('首页')
//   // res.send('首页')
//   // sendFile 只适合返回单个静态资源
//   res.sendFile(path.join(__dirname, './views/about.html'))
// })

// 默认打开 views 下面的 index.html  
//  http://127.0.0.1:3000 
// app.use(express.static(path.join(__dirname, './views')))
// //  http://127.0.0.1:3000/assets/ 
// app.use('/assets', express.static(path.join(__dirname, './assets')))


app.get('/api/getdata', (req, res) => {
  res.send({
    code: 0,
    message: [

    ]
  })
})
app.listen(3000, () => {
  console.log('http://127.0.0.1:3000')
})

artTemplate模块 的html文件书写方式

<body>
  首页
  <!-- <img src="../assets/1.jpeg" alt=""> -->
  <!-- 标准语法  -->
  <!-- <p>
    {{name}}
  </p>
  <p>
    {{age}}
  </p>

  <p>
    {{each hobby}}
      {{$index}} {{$value}}
    {{/each}}
  </p> -->

  <!-- 原始语法 -->
  <p>
    <%=name%>
  </p>
  <p>
    <%=age%>
  </p>
  <p>
    <%for(var i = 0; i < hobby.length;i++){%>
      <%=hobby[i]%>
    <%}%>
  </p>
</body>

服务器渲染的标准模块ejs

const express = require('express')
const path = require('path')

const ejs = require('ejs')

const app = express()

// 配置模板引擎 ejs 
// app.set('view engine', 'ejs')
// // 配置模板的位置 , 文件需要是 .ejs 结尾 
// app.set('views', path.join(__dirname, './views'))

// 配置模板引擎 html 
app.set('view engine', 'html')
app.engine('html', ejs.__express)

app.get('/index.html', (req, res) => {

  var obj = {
    name: 'fly',
    age: 18,
    hobby: ['吃饭', '睡觉', '上号']
  }
  // 3. 通过render 渲染
  res.render('index', obj)

})
app.listen(3000, () => {
  console.log('http://127.0.0.1:3000')
})

ejs模板html构成的ejs文件

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  首页
  <!-- <img src="../assets/1.jpeg" alt=""> -->
  <h2>标准语法 </h2>
  <p>
    {{name}}
  </p>
  <p>
    {{age}}
  </p>

  <p>
    {{each hobby}}
    {{$index}} {{$value}}
    {{/each}}
  </p>

  <h2> 原始语法</h2>
  <p>
    <%=name%>
  </p>
  <p>
    <%=age%>
  </p>
  <p>
    <%for(var i=0; i < hobby.length;i++){%>
      <%=hobby[i]%>
        <%}%>
  </p>
</body>

</html>

老师总结内容

  1. node创建原生web服务 了解

  2. express

  • 创建服务

  • 静态资源托管

    res.sendFile 单个

    默认打开 index.html
    app.use(express.static('./views'))

  • 服务端渲染 了解

    • art-template

    • ejs

      • 方式1 ejs 视图

      app.set('view engine','ejs')
      app.set('views',path.join(__dirname,'./views))

      res.render('index.ejs',obj)

      • 方式2 html 视图

      cons ejs = require('ejs')

      app.set('view engine','html')
      app.engine('html',ejs.__express)

      res.render('index.html',obj)

  1. 服务端渲染和客户端渲染有什么区别
SEO(Search Engine Optimization)

“搜索引擎优化” 如何迎合搜索引擎的规则,使得网站在搜索结果中能有更好的排名

服务端渲染

用传统的servlet开发来举例:浏览器请求servlet,servlet在服务端生成html响应给浏览器,浏览器展示html 的内容,这个过程就是服务端渲染

服务端渲染的特点:
1)在服务端生成html网页的dom元素。 2)客户端(浏览器)只负责显示dom元素内容。

  • 缺点

不利于网站进行SEO,因为网站大量使用javascript技术,不利于spider抓取网页。

  • 优点

客户端负责渲染,用户体验性好,服务端只提供数据不用关心用户界面的内容,有利于提高服务端的开发效率。

  • 适用场景

对SEO没有要求的系统,比如后台管理类的系统,如电商后台管理,用户管理等。
`

客户端渲染

客户端(浏览器) 使用AJAX向服务端发起http请求,获取到了想要的数据,客户端拿着数据开始渲染html网页,生成Dom元素,并最终将网页内容展示给用户
客户端渲染的特点:
1)在服务端只是给客户端响应的了数据,而不是html网页 2)客户端(浏览器)负责获取服务端的数据生成Dom元素。

  • 缺点

不利于网站进行SEO,因为网站大量使用javascript技术,不利于spider抓取网页。

  • 优点

客户端负责渲染,用户体验性好,服务端只提供数据不用关心用户界面的内容,有利于提高服务端的开发效率。

  • 适用场景

对SEO没有要求的系统,比如后台管理类的系统,如电商后台管理,用户管理等。`

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容