DIV CSS 佈局教程網

Node.js 如何用 HTTPS 物件發起 POST 請求
編輯:JavaScript綜合知識     

Node.js 官方文件對 https 模組的描述相當簡潔,很多細節得自己摸索。本文記錄一個實際案例:在註冊流程的某一步,需要把表單資料 POST 到一個 HTTPS 端點。

基本流程

整個過程可以拆成四步:組出 URL、解析成 options 物件、設定 method 與 headers、最後用 https.request 送出並寫入 body。

var util = require('util'),
    https = require('https'),
    url = require('url'),
    querystring = require('querystring');

var regUrl = "https://ssl.mail.163.com/regall/unireg/call.do;jsessionid=%s?cmd=register.start"
           + "&adapter=%s&reforward=common/reform&targetCmd=register.ctrlTop";

var cookie = 'a=b;c=d;',
    mail   = 'regUsername',
    pass   = 'password',
    vcode  = 'abcde';

var _regUrl = util.format(regUrl, 'id123455', 'param2');

// 把字串解析成 options 物件
var post_option = url.parse(_regUrl);
post_option.method = 'POST';
post_option.port = 443;

// 準備要送出的表單資料
var post_data = querystring.stringify({
  'name'           : mail,
  'uid'            : mail + '@163.com',
  'confirmPassword': pass,
  'password'       : pass,
  'vcode'          : vcode,
  'flow'           : 'main',
  'from'           : '163mail_right',
  'mobile'         : ''
});

post_option.headers = {
  'Content-Type'  : 'application/x-www-form-urlencoded',
  'Content-Length': Buffer.byteLength(post_data),
  'Cookie'        : cookie
};

var post_req = https.request(post_option, function(res){
  res.on('data', function(buffer){
    console.log(buffer.toString());
  });
});

// 寫入 body 並結束請求
post_req.write(post_data);
post_req.end();

幾個容易踩到的細節

  • Content-Type 必須對。表單格式是 application/x-www-form-urlencoded,若送 JSON 就要改成 application/json 並用 JSON.stringify,否則後端收到的 body 會解析不出來。
  • Content-Length 建議用 Buffer.byteLength()。直接用 post_data.length 在純 ASCII 時沒問題,但一旦內容含中文,字元數與位元組數不同,伺服器會因為長度不符而截斷或等待逾時。
  • 記得呼叫 end()。只呼叫 write() 而不 end(),請求不會真正送出。
  • 別忘了傾聽 error。正式環境請加上 post_req.on('error', ...),否則連線層的錯誤會直接讓行程崩潰。

現代寫法參考

如果使用的 Node 版本支援 Promise 與 async/await,可以改用內建的 fetch(Node 18 以上)或 axios 這類套件,程式碼會短很多:

const res = await fetch(_regUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Cookie': cookie
  },
  body: post_data
});
console.log(await res.text());

不過理解底層 https.request 的用法仍然值得——需要自訂 TLS 憑證、proxy 或特殊 header 時,还是得回到這一層來控制。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved