想要写接口, 首先你得知道什么是content-type

393 阅读1分钟

如何理解content-type?

content-type用英文翻译过来就是内容类型,content-type可以定义网络文件中的类型和网页编码,浏览器会根据请求处理返回的内容

content-type的作用

在http协议中,content-type的作用至关重要,如果你在请求体中设置content-type,那么就能告诉服务器本次携带的是什么类型的数据,如果在响应头中设置content-type,就能告诉服务器本次返回的数据是什么类型的

常见content-type文件类型

  • htmlres.setHeader('content-type', 'text/html;charset=utf8')
  • cssres.setHeader('content-type', 'text/css;charset=utf8')
  • jsres.setHeader('content-type', 'application/javascript')
  • pngres.setHeader('content-type', 'image/png')
  • jsonres.setHeader('content-type', 'application/json;charset=utf-8')
content-type格式

res.setHeader('content-type', 值)

代码示例
const http = require('http')
const fs = require('fs')
const path = require('path')
const server = http.createServer((req, res) => {
  if(url === '/' || url === '/index.html') {
    // 读出文件内容并返回
    res.setHeader('content-type', 'text/html;charset=utf8');

    res.end(content)
  } 
}

server.listen(8000, ()=>{
  console.log('服务器已启动');
})