美文网首页
http响应内容类型:Content-Type

http响应内容类型:Content-Type

作者: 似朝朝我心 | 来源:发表于2020-11-09 19:43 被阅读0次

http网络服务构建模块

const http = require('http')
const server = http.createServer()
server.on('request', (req, res) => {
res.end('hello,你好啊!')
})
server.listen(8080,() => {
  console.log('Server is running at:http://localhost:8080')
})
  • 上述代码会产生中文乱码。


  • 为什么会产生中文乱码呢?
    在服务器端默认发送的数据,采用的是utf-8编码的内容,但是我们的浏览器是不能准确知道你是utf-8编码的内容,所以浏览器会在不知道服务器响应内容的编码的情况夏,会按照我们当前操作系统的默认编码去解析,而我们中文window操作系统默认是gbk编码。

  • 所以解决中文乱码的正确方法是告诉浏览器,我给你发送的内容是什么编码的(添加如下代码进去)。

res.setHeader('Content-Type', 'text/plain; charset=utf-8')
  • 在http协议中,Content-Type就是用来告知对方,你给对方发送的数据内容是什么类型的,"您好!先生(客户端浏览器),我发送的是text-plain普通文本哦,麻烦你用utf-8编码给用户解析下。"


  • 那对方(浏览器)到底有没有接收到我们传达的话语呢?有的。我们可以看它的响应头Response Headers。


  • 如果你选择了发送html文本,带有h5等标签,则需告知浏览器你发送的文本类型是text/html,否则将会当成字符串被解析,而不是当成标签。
const http = require('http')
const server = http.createServer()
server.on('request', (req, res) => {
  res.setHeader('Content-Type', 'text/html; charset=utf-8')
  res.end(`
  <h1>你好啊!</h1>
  <br>
  <button>点我有惊喜!</button>
  `)
})
server.listen(8080, () => {
  console.log(`Server is running at:http://localhost:8080`)
})

客户端通过域名向服务器发送请求,服务器响应内容返回给客户端的浏览器。

  • 上面的代码我们已经尝试过用一个简单的方法生成1个htpp服务器,然后发送字符串给客户端浏览器,但我们知道真实的环境下是一个个的单文件响应给浏览器,然后渲染成视图界面。
    例如:我们访问百度域名,响应在浏览器的文件有:



    这些文件就渲染成如下的完整视图。


模仿服务器响应内容给客户端浏览器,结合fs文件系统发送文件中的数据。

准备如下类型的文件,写入简单的内容。



首先就需要发送文件给服务器,然后将文件中的内容给响应给浏览器。

const http = require('http')
const fs = require('fs')
const server = http.createServer()
server.on('request', (req, res) => {
  let url = req.url
  console.log(url)
  if (url === '/') {
    //发送文件给服务器
    fs.readFile('./data/views/source/index.html', (err, data) => {
      if (err) {
        res.setHeader('Content-Type', 'text/plain; charset=utf-8')
        console.log('文件读取失败')
      }else {
        //data 默认是二进制数据,可以通过toString转为字符串
        //res.end()支持2种数据类型,分别是二进制、字符串
        res.setHeader('Content-Type', 'text/html; charset=utf-8')
        res.end(data)
      }
    })
  }
})
server.listen(8080, () => {
  console.log(`Server is running at:http://localhost:8080`)
})

我们就可以看到了浏览器响应的index.html界面了。



我们将本地的index.html文件上传到服务器后,我们可以在index.html里面继续编写代码,服务器会动态更新index.html页面,不需要每次都要首先去重新关掉服务器,待内容写完后,然后启动服务器的繁琐步骤。

例如我们来添加一个按钮标签。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>hello world!</h1>
    <h2>You are beautiful!</h2>
    <button>bell!</button>
</body>
</html>
  • 响应图片
else if (url === '/xingkong') {
    fs.readFile('./data/views/source/xingkong.jpg', (err, data) => {
      if (err) {
        res.setHeader('Content-Type', 'text/plain; charset=utf-8')
        console.log('文件读取失败')
      } else {
        //图片不需要指定编码,图片文件类型为:image/jpeg
        res.setHeader('Content-Type', 'image/jpeg')
        res.end(data)
      }
    })
  }

url又叫统一资源定位符,一个url对应一个资源,这里的资源指的是我们的文件,比如我们的url === '/xingkong'对应的资源便是'./data/views/source/xingkong.jpg'
  • 通过上面2个demo,我们得知发送数据,必须指定Content-Type的文件类型,不同资源对应的Content-Type是不一样的。

文件拓展名对应的Content-Type类型查找网址:
https://tool.oschina.net/commons

常见的有:
.css对应text/css
.txt对应text/plain
.html对应text/html
.jpg或jpeg对应image/jpeg
.png对应image/png
.js对应application/x-javascript

小结:



抽离思想:

抽离固定的路径:const dir = './data/views/source'

const http = require('http')
const fs = require('fs')
const server = http.createServer()
server.on('request', (req, res) => {
  let url = req.url
  const dir = './data/views/source'
  if (url === '/') {
    //发送文件给服务器
    fs.readFile(`${dir}/index.html`, (err, data) => {
      if (err) {
        res.setHeader('Content-Type', 'text/plain; charset=utf-8')
        console.log('文件读取失败')
      } else {
        res.setHeader('Content-Type', 'text/html; charset=utf-8')
        res.end(data)
      }
    })
  } else if (url === '/xingkong') {
    fs.readFile(`${dir}/xingkong.jpg`, (err, data) => {
      if (err) {
        res.setHeader('Content-Type', 'text/plain; charset=utf-8')
        console.log('文件读取失败')
      } else {
        //图片不需要指定编码,图片文件类型为:image/jpeg
        res.setHeader('Content-Type', 'image/jpeg')
        res.end(data)
      }
    })
  }
})

server.listen(8080, () => {
  console.log(`Server is running at:http://localhost:8080`)
})

绑定动态路径:

const http = require('http')
const fs = require('fs')
const server = http.createServer()
server.on('request', (req, res) => {
  let url = req.url
  console.log(url)
  const dir = './data/views/source'
  let filePath = '/index.html'
  if (url !== '/') {
    filePath = url
  }

  fs.readFile(`${dir}${filePath}`, (err, data) => {
    if (err) {
      res.setHeader('Content-Type', 'text/plain; charset=utf-8')
      return res.end('404 Not Found')
    }
    res.end(data)
  })
})
server.listen(8080, () => {
  console.log(`Server is running at:http://localhost:8080`)
})

相关文章

网友评论

      本文标题:http响应内容类型:Content-Type

      本文链接:https://www.haomeiwen.com/subject/zkekbktx.html