Node 內建 `https` 模組提供 `request()` 方法發起 TLS 連線。需手動處理:URL 解析、Header 組裝、資料寫入、回應串流處理。
const https = require('https');
const querystring = require('querystring');
const url = require('url');
// 目標 URL(含動態參數)
const regUrl = 'https://ssl.mail.163.com/regall/unireg/call.do;jsessionid=%s?cmd=register.start&adapter=%s&reforward=common/reform&targetCmd=register.ctrlTop';
const sessionId = 'id123455';
const adapter = 'param2';
const targetUrl = util.format(regUrl, sessionId, adapter); // 需 require('util')
// POST 表單資料
const postData = querystring.stringify({
name: 'regUsername',
uid: 'regUsername@163.com',
confirmPassword: 'password',
password: 'password',
vcode: 'abcde',
flow: 'main',
from: '163mail_right',
mobile: ''
});
// 解析 URL 獲取選項
const options = url.parse(targetUrl);
options.method = 'POST';
options.port = 443;
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData), // 必須用 Buffer.byteLength 計算位元組長度
'Cookie': 'a=b;c=d;' // 攜帶 Cookie
};
// 發起請求
const req = https.request(options, (res) => {
console.log('狀態碼:', res.statusCode);
console.log('回應 Headers:', res.headers);
let rawData = '';
res.setEncoding('utf8');
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsed = JSON.parse(rawData);
console.log('解析後回應:', parsed);
} catch (e) {
console.log('原始回應:', rawData);
}
});
});
// 錯誤處理
req.on('error', (e) => {
console.error('請求錯誤:', e.message);
});
// 寫入資料並結束
req.write(postData);
req.end();
| 細節 | 說明 |
|---|---|
Content-Length | 必須為 **Buffer 位元組長度**,非字串長度。中文字符 UTF-8 佔 3 字節,用 `Buffer.byteLength(str)` 計算。 |
| Cookie 處理 | 手動拼接 `Cookie` header。複雜場景建議用 `tough-cookie` 管理 Cookie Jar,自動處理 `Set-Cookie`、過期、Domain/Path。 |
| Redirect (302) | `https.request` **不自動跟隨重導向**。需檢查 `res.statusCode === 302` 並讀取 `res.headers.location` 手動發起新請求。 |
| 憑證驗證 | 預設驗證 CA。開發環境可設 `rejectUnauthorized: false` 略過自簽憑證(生產嚴禁)。 |
| 連線複用 | 預設 `keep-alive`。大量請求建議使用 `Agent` 控制 `maxSockets`。 |
const axios = require('axios');
axios.post(targetUrl, postData, { headers: options.headers })
.then(res => console.log(res.data))
.catch(err => console.error(err));
const res = await fetch(targetUrl, {
method: 'POST',
headers: options.headers,
body: postData
});
const data = await res.text(); // 或 res.json()