You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在服务端JavaScript的HTTP.Get中设置字符集?返回乱码求助

Hey Terry, let's sort out that annoying garbled response issue you're hitting with your server-side JavaScript HTTP requests. Garbled text almost always boils down to incorrect character encoding handling when parsing the server's response. Here are a few targeted solutions tailored to your code and use case:

解决HTTP请求返回乱码的字符集设置方案

1. 直接指定响应的字符编码(最常用)

Most modern APIs and servers use utf-8 encoding, so explicitly telling your request handler to parse the response with this charset will fix most garbled text issues. Below's how to adjust your code, and a quick note: your requestToken call should be a POST request (since you're sending a payload with credentials) instead of GET—this might have also contributed to unexpected responses.

Example with Node.js native https module:

const https = require('https');

var url = 'https://auth.exacttargetapis.com/v1/requestToken';
var contentType = 'application/json';
var payload = '{"clientId":"zcb2e6uqb9jqylp8qq8aw6ju","clientSecret":"nYfUJpCoZb3LO3XQAEAw4tGv"}';

const options = {
  method: 'POST', // Critical: POST is required for sending payloads to token endpoints
  headers: {
    'Content-Type': contentType,
    'Content-Length': Buffer.byteLength(payload)
  }
};

const req = https.request(url, options, (res) => {
  // *Key step*: Set the response encoding to utf-8
  res.setEncoding('utf8');
  
  let responseData = '';
  res.on('data', (chunk) => {
    responseData += chunk;
  });
  
  res.on('end', () => {
    console.log('Decoded response:', responseData); // No more garbled text!
  });
});

req.on('error', (err) => {
  console.error('Request error:', err);
});

req.write(payload);
req.end();

2. Dynamically extract encoding from response headers

Some servers specify the charset in the Content-Type response header (e.g., application/json; charset=utf-8). You can parse this header to use the exact encoding the server specifies, making your code more flexible:

const https = require('https');

https.get('your-target-url', (res) => {
  // Extract charset from Content-Type header
  const contentTypeHeader = res.headers['content-type'];
  const charsetMatch = contentTypeHeader?.match(/charset=([^;]+)/);
  const encoding = charsetMatch ? charsetMatch[1] : 'utf-8'; // Fallback to utf-8 if no charset is specified
  
  res.setEncoding(encoding);
  
  let decodedData = '';
  res.on('data', (chunk) => decodedData += chunk);
  res.on('end', () => {
    console.log('Dynamically decoded content:', decodedData);
  });
});

3. Handle binary content (like your example image)

For non-text resources like images, do not set a character encoding—use Buffer to collect binary data instead. Setting an encoding here will corrupt the binary content:

const https = require('https');
const fs = require('fs');

var imgURL = 'https://www.cathaypacific.com/content/dam/focal-point/digital-library/global-marketing/gatwick/Gatwick_airport_convenience.jpg/_jcr_content...';

https.get(imgURL, (res) => {
  const binaryChunks = [];
  res.on('data', (chunk) => binaryChunks.push(chunk));
  
  res.on('end', () => {
    const imageBuffer = Buffer.concat(binaryChunks);
    // Save the image to file or process the binary data
    fs.writeFileSync('gatwick-airport.jpg', imageBuffer);
    console.log('Image saved successfully (no corruption!)');
  });
});

Quick Notes

  • Double-check your request method: Token endpoints like requestToken almost always require POST, not GET. Using GET with a payload can lead to unexpected, unparsable responses that look like garbled text.
  • If you're using a specific SDK (like ExactTarget's official library), check its documentation for built-in encoding settings—many SDKs handle this automatically.

内容的提问来源于stack exchange,提问作者Terry Nong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:09:32