zoukankan      html  css  js  c++  java
  • Node.js 之ContentType内容类型

    • 结合 fs 发送文件中的数据
    • Content-Type,查看内容类型:http://tool.oschina.net/commons
    • 不同的资源对应的 Content-Type 是不一样的
    • 图片不需要指定编码
    • 一般只为字符数据才指定编码
    var http = require('http')
    var fs = require('fs')
    
    var server = http.createServer()
    
    server.on('request', function (req, res) {
      // / index.html
      var url = req.url
    
      if (url === '/') {
        // 肯定不这么干
        // res.end('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><h1>首页</h1></body>/html>')
    
        // 要发送的还是在文件中的内容
        fs.readFile('./resource/index.html', function (err, data) {
          if (err) {
            res.setHeader('Content-Type', 'text/plain; charset=utf-8')
            res.end('文件读取失败,请稍后重试!')
          } else {
            // data 默认是二进制数据,可以通过 .toString 转为咱们能识别的字符串
            // res.end() 支持两种数据类型,一种是二进制,一种是字符串
            res.setHeader('Content-Type', 'text/html; charset=utf-8')
            res.end(data)
          }
        })
      } else if (url === '/baby') {
        // url:统一资源定位符
        // 一个 url 最终其实是要对应到一个资源的
        fs.readFile('./resource/ab2.jpg', function (err, data) {
          if (err) {
            res.setHeader('Content-Type', 'text/plain; charset=utf-8')
            res.end('文件读取失败,请稍后重试!')
          } else {
            // data 默认是二进制数据,可以通过 .toString 转为咱们能识别的字符串
            // res.end() 支持两种数据类型,一种是二进制,一种是字符串
            // 图片就不需要指定编码了,因为我们常说的编码一般指的是:字符编码
            res.setHeader('Content-Type', 'image/jpeg')
            res.end(data)
          }
        })
      }
    })
    
    server.listen(3000, function () {
      console.log('Server is running...')
    })
    
    • 默认访问 :http://localhost:3000/
      在这里插入图片描述

    • 访问图片路径:http://localhost:3000/img
      在这里插入图片描述

    本文来自博客园,作者:兮动人,转载请注明原文链接:https://www.cnblogs.com/xdr630/p/15254827.html

  • 相关阅读:
    保护模式下通过写显存在屏幕上输出字符串
    Linux0.01 引导代码分析-head.s
    OpenGL Super Bible 第四章 Transform 程序绘图部分代码解析
    Ubuntu10.04 下编译 OpenOffice DEV300 分支
    今天把博客开通了,欢迎来访!
    沟通的工具ER图
    为什么博客叫秋水?
    mysql.基础笔记
    如何阅读别人的C代码
    Github搜索与查看
  • 原文地址:https://www.cnblogs.com/xdr630/p/15254827.html
Copyright © 2011-2022 走看看