[英]Socket hang up when using axios.get, but not when using https.get
[英]Node `https.get` returns 403, `axios.get` and `curl` return 200
我正在嘗試使用 Node 的本機https
模塊和 3rd 方axios
模塊(非常常用)執行 GET 請求:
const endpoint = 'https://www.pathofexile.com/api/trade/data/stats';
require('axios')
.get(endpoint)
.then(response => console.log('axios', response.status));
// prints 200
require('https')
.get(endpoint, {},
response => console.log('https', response.statusCode));
// prints 403
axios
請求按預期工作正常; 我也可以查看response.data
。 但是https
請求失敗並顯示 403。
curl
也可以正常工作。 由於https
過去可以工作,我的預感是服務器必須更改某些內容,並且https.get
和axios.get
必須做一些稍微不同的事情(例如,默認情況下發送不同的標頭),服務器不再對此漠不關心。
測試的一點點后,我注意到,默認情況下, https
模塊不包括User-Agent
頭,而axios
和curl
都這樣做。 服務器拒絕您的請求,因為您沒有設置User-Agent
。
要解決此問題,只需指定您選擇的自定義User-Agent
:
require('https')
.get(endpoint, {headers: {'User-Agent': 'whatever'}},
response => console.log('https', response.statusCode));
在關注節點 https 的幾個網絡結果沒有找到答案之后,我發現另一個關於 python 的stackoverflow 帖子返回 403 而 curl 返回 200。
事實證明,這是請求的'User-Agent'
標頭的問題。
Curl 默認發送用戶代理'curl/7.72.0'
:
> GET /94548/2401383/manifest.js HTTP/1.1
> Host: cdn.flashtalking.com
> User-Agent: curl/7.72.0
> Accept: */*
Axios 默認發送用戶代理'axios/0.20.0\\r\\n'
:
_header: 'GET /api/trade/data/stats HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'User-Agent: axios/0.20.0\r\n' +
'Host: www.pathofexile.com\r\n' +
'Connection: close\r\n' +
'\r\n',
雖然默認情況下節點的 https 不發送用戶代理:
_header: 'GET /api/trade/data/stats HTTP/1.1\r\n' +
'Host: www.pathofexile.com\r\n' +
'Connection: close\r\n' +
'\r\n',
顯然,服務器現在檢查非空的User-Aagent
標頭。 更新 https 請求會得到 200:
const endpoint = 'https://www.pathofexile.com/api/trade/data/stats';
require('axios')
.get(endpoint)
.then(response => console.log('axios', response.status));
// prints 200
require('https')
.get(endpoint, {},
response => console.log('https', response.statusCode));
// prints 403
require('https')
.get(endpoint, {header: {headers: {'User-Agent': '_'}}}},
response => console.log('https', response.statusCode));
// prints 200
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.