Skip to content

Commit 613d9cf

Browse files
committed
update tips
1 parent 82d4b06 commit 613d9cf

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

dist/utils.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,28 @@ async function post({ url, body, header, json }) {
5656
// noinspection DuplicatedCode
5757
const req = (url_.protocol === "http:" ? http_1.default : https_1.default).request(options, (res) => {
5858
let responseBody = '';
59+
// 根据 Content-Type 头获取字符编码
60+
const contentType = res.headers['content-type'];
61+
let charset = 'utf-8'; // 默认字符编码
62+
// 解析 Content-Type 以获取编码,如果有指定编码
63+
if (contentType) {
64+
const match = contentType.match(/charset=([\w-]+)/i);
65+
if (match) {
66+
if (match[1].toLowerCase() === 'utf-8') {
67+
charset = 'utf-8';
68+
}
69+
else if (match[1].toLowerCase() === 'gbk') {
70+
charset = 'ascii';
71+
}
72+
else if (match[1].toLowerCase() === 'ascii') {
73+
charset = 'ascii';
74+
}
75+
else {
76+
charset = 'utf-8'; // 默认字符编码
77+
}
78+
}
79+
}
80+
res.setEncoding(charset);
5981
res.on('data', (chunk) => {
6082
responseBody += chunk;
6183
});

src/utils.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,27 @@ export async function post({url, body, header, json}: any): Promise<string> {
5252
const req = (url_.protocol === "http:" ? http : https).request(options, (res) => {
5353
let responseBody = '';
5454

55+
// 根据 Content-Type 头获取字符编码
56+
const contentType = res.headers['content-type'];
57+
let charset: BufferEncoding = 'utf-8'; // 默认字符编码
58+
59+
// 解析 Content-Type 以获取编码,如果有指定编码
60+
if (contentType) {
61+
const match = contentType.match(/charset=([\w-]+)/i);
62+
if (match) {
63+
if (match[1].toLowerCase() === 'utf-8') {
64+
charset = 'utf-8';
65+
} else if (match[1].toLowerCase() === 'gbk') {
66+
charset = 'ascii';
67+
} else if (match[1].toLowerCase() === 'ascii') {
68+
charset = 'ascii';
69+
} else {
70+
charset = 'utf-8'; // 默认字符编码
71+
}
72+
}
73+
}
74+
res.setEncoding(charset);
75+
5576
res.on('data', (chunk) => {
5677
responseBody += chunk;
5778
});

0 commit comments

Comments
 (0)