node express框架下接收、发送和解析iso-8869-1编码

1、在中间件接收

// 文档写着编码有两种,utf-8和iso-8859-1二选一,默认为utf-8,如果要调整为iso-8859-1,extended需要为true
app.use(bodyParser.text({defaultCharset:'iso-8859-1'}));
app.use(bodyParser.urlencoded({
    extended: true
}));

2、res返回

 // 头部设置content-type的类型和编码
 res.set('Content-Type', 'text/plain; charset=iso-8859-1')
 // 此处注意用write和end,因为send已经只支持utf-8
 res.write(utf8)
 res.end()

3、解码问题

// 使用第三方包iconv-lite
const iconv = require('iconv-lite')
// 用sublime建立一个iso-8859-1文件,内有中文"你好"和英文"hello"
// 用latin1读取文件
const file = fs.readFileSync('./test-iso', { encoding: 'latin1' })
// 解码 得到utf-8编码
const  utf8 = iconv.decode(file, 'utf8');

小demo:

const fs = require('fs')
const express = require('express')
const axios = require('axios')
const iconv = require('iconv-lite')
const bodyParser = require('body-parser');
const app = express()

// 跨域问题
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
    res.header('Access-Control-Allow-Methods', 'POST,GET,OPTIONS');
    res.header('Content-Type', 'multipart/form-data;charset=utf-8');
    res.header('Content-Type', 'application/json;charset=utf-8');

    if (req.method === 'OPTIONS') res.send(200);
    next();
});

// app.use(bodyParser.text());
app.use(bodyParser.text({defaultCharset:'iso-8859-1'}));
app.use(bodyParser.urlencoded({
    extended: true
}));

app.get('/', async function (req, res) {
    // 读取iso-8859-1文件
    const file = fs.readFileSync('./test-iso', { encoding: 'latin1' })
    console.log(file, '===file=====');
    console.log();
    // 转码
    let utf8 = iconv.decode(file, 'utf8');
    console.log(utf8, '===utf8=====');
    console.log();
    // 请求接口2
    const result = await axios.post('http://127.0.0.1:3001',
        utf8,
        {
            headers: {
                'Content-Type': 'text/plain; charset=iso-8859-1'
            },
        })
        .then(resp => {
            console.log(resp.data,'<==============resp==================');
            return resp
        })
    // 设置返回值编码
    res.set('Content-Type', 'text/plain; charset=iso-8859-1')
    res.write(utf8)
    res.end()
})

app.post('/', function (req, res) {
    // 接受为iso-8859-1
    const body = req.body
    console.log(body, '===body=====');
    console.log();
    // 转码
    let tempBuffer = Buffer.from(body);
    tempBuffer = iconv.decode(body, 'utf8');
    // tempBuffer = iconv.decode(tempBuffer, 'utf8');
    console.log(tempBuffer, '===tempBuffer=====');
    console.log();

    res.set('Content-Type', 'text/plain; charset=iso-8859-1')
    res.write(tempBuffer)
    res.end()
})

app.listen(3001)

请求get接口127.0.0.1:3001返回值:

ä½ å¥½
hello ===file=====

你好
hello ===utf8=====

ä½ å¥½
hello ===body=====

你好
hello ===tempBuffer=====

你好
hello <==============resp==================
posted @ 2021-08-10 10:46  fengyujia  阅读(115)  评论(0编辑  收藏  举报