let host = req.headers.host
console.log(host)
列印localhost:3000。到現在為止還挺好。
console.log(host === "localhost:3000")
列印false。嗯?
console.log(host.length)
console.log("localhost:3000".length)
印刷品15和14。我們的神秘字串長了一個字符?讓我們一個一個地看每個字符。
for (var i = 0; i < host.length; i ) {
console.log(i, host.charAt(i));
}
印刷:
0 l
1 o
2 c
3 a
4 l
5 h
6 o
7 s
8 t
9 :
10 6
11 0
12 6
13 4
14 3
一次列印一個字符顯示冒號后現在有 5 個數字:60643。什么?
每次我重新啟動 Web 服務器時,此結果都會發生變化。例如,上次運行是63275,上次運行是54313。
console.log(host)在 for 回圈后立即添加確認字串仍然是localhost:3000。這里發生了什么?
問這個問題我幾乎感到瘋狂,但我已經看了一整天,而且 100% 的時間都會發生這種情況。環境:最新版本的Node(v17.3.0),macOS Monterey(M1 mac)。
跟進
- 此處可重現的示例(需要一個免費的Vercel帳戶)
typeof host回報string- 以下是字串每個字符的附加除錯資訊:
i |
charAt(i) |
charCodeAt(i) |
codePointAt(i).toString(16) |
|---|---|---|---|
| 0 | 升 | 108 | 6c |
| 1 | ○ | 111 | 6f |
| 2 | C | 99 | 63 |
| 3 | 一個 | 97 | 61 |
| 4 | 升 | 108 | 6c |
| 5 | H | 104 | 68 |
| 6 | ○ | 111 | 6f |
| 7 | 秒 | 115 | 73 |
| 8 | 噸 | 116 | 74 |
| 9 | : | 58 | 3a |
| 10 | 5 | 53 | 35 |
| 11 | 4 | 52 | 34 |
| 12 | 8 | 56 | 38 |
| 13 | 6 | 54 | 36 |
| 14 | 2 | 50 | 32 |
uj5u.com熱心網友回復:
根據檔案:
該vercel dev的命令用于在本地復制Vercel部署環境,讓您測驗您的無服務器功能,而不需要你做出改變,每次部署。
出于這個原因,像這樣/api/hello的呼叫是由運行隨機空閑埠的本地代理服務器處理的。
最有趣的事情開始了:對于代理服務器的標準輸出(stdout)(當然console.log也有),代理埠被替換為開發埠(感覺就像是一個過時的遺留):
p.stdout.on('data', (data: string) => {
process.stdout.write(data.replace(proxyPort, devPort));
});
出于這個原因,req.headers.host和的長度存在差異localhost:3000,以及為什么它們在 中看起來相同console.log,但在比較時不相等。
因此,例如使用x-forwarded-host標題而不是host:
console.log((
req.headers['x-forwarded-host'] || req.headers.host
) === "localhost:3000");
res.status(200).json(req.headers);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/399301.html
