Node.js 之发送文件数据编码问题

node.js中编码问题

  • 在服务端默认发送的数据,其实是 utf8 编码的内容
  • 但是浏览器不知道你是 utf8 编码的内容
  • 浏览器在不知道服务器响应内容的编码的情况下会按照当前操作系统的默认编码去解析
  • 中文操作系统默认是 gbk
  • 解决方法就是正确的告诉浏览器我给你发送的内容是什么编码的
// require
// 端口号

var http = require('http')

var server = http.createServer()

server.on('request', function (req, res) {
 
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('hello 世界')

server.listen(3000, function () {
  console.log('Server is running...')
})

在这里插入图片描述
在这里插入图片描述

  • 在 http 协议中,Content-Type 就是用来告知对方我给你发送的数据内容是什么类型
  • 可以在node.js中文网的API下找到HTTP:http://nodejs.cn/api/http.html
    res.setHeader('Content-Type','text/plain; charset=utf-8')

测试:

var http = require('http')

var server = http.createServer()

server.on('request',function(req,res){
    res.setHeader('Content-Type','text/plain; charset=utf-8')
    res.end('hello 世界!')
})



server.listen(3000,function(){
    console.log('Server is running...');
})

在这里插入图片描述

在这里插入图片描述

根据路径浏览器解析不同的内容

  • text/plain就是普通文本
  • 发送的是 html格式的字符串,则也要告诉浏览器我给你发送是text/html格式的内容
var http = require('http')

var server = http.createServer()

server.on('request', function (req, res) {

var url = req.url

  if (url === '/plain') {
    // text/plain 就是普通文本
    res.setHeader('Content-Type', 'text/plain; charset=utf-8')
    res.end('hello 世界')
  } else if (url === '/html') {
    // 如果你发送的是 html 格式的字符串,则也要告诉浏览器我给你发送是 text/html 格式的内容
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    res.end('<p>hello html <a href="">点我</a></p>')
  }
})

server.listen(3000, function () {
  console.log('Server is running...')
})
  • 请求:localhost:3000/plain

在这里插入图片描述

  • 请求:localhost:3000/html

在这里插入图片描述

  • 访问百度发现响应的是字符串,只有浏览器能解析识别出来
    在这里插入图片描述

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

原文地址:https://www.cnblogs.com/xdr630/p/15254828.html