問題現象
底下這段程式碼在跨域呼叫時,會收到 501 的錯誤回應:
$.ajax({
type: "POST",
url: "https://192.168.1.202/sensordata.php",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(ajaxPostData),
dataType: 'json',
success: function(data){
// 請求成功時的處理
console.info("success.");
if (data["status"] == "ok"){
alert("Settings is Ok. The Machine is rebooting.");
}
},
error: function(xhr, ajaxOptions, thrownError) {
// 請求失敗時的處理
console.info("error.");
if (xhr.status == 200) {
alert(ajaxOptions);
} else {
alert(xhr.status);
alert(thrownError);
}
}
});
解法
把 contentType: 'application/json; charset=utf-8' 這一行拿掉即可。
背後的原因
這就要從瀏覽器的「預檢請求」(preflight)機制說起:
application/x-www-form-urlencoded、multipart/form-data 與 text/plain。一旦你指定了 application/json,瀏覽器就會先自動送出一個 method 為 OPTIONS 的請求,用來詢問伺服器「我接下來要用什麼方法、帶什麼標頭」。Access-Control-Allow-Methods(也就是 Allow 相關標頭)中明確列出被允許的方法。換句話說,501 並不是你的 POST 出了問題,而是那個你沒看見的 OPTIONS 預檢沒被正確應對。除了移除自訂的 Content-Type,另一條路是在伺服器端補上完整的 CORS 標頭與 OPTIONS 處理:
// 以 Node.js/Express 為例的概念示意
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
return res.sendStatus(204);
}
參考資料:跨域與 Content-Type 的關係
以上就是這次排查的整理。跨域時先把「瀏覽器可能多送一個請求」這件事放在心裡,很多看似莫名的錯誤碼都能很快定位。