1. 程式人生 > 其它 >node express框架下接收、傳送和解析iso-8869-1編碼

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==================