Node.JS環境下處理第三方API返回403錯誤
在使用Node.js調用第三方網站API時,經常會遇到403錯誤。例如,API地址https://core-api.prod.blur.io/v1/prices在瀏覽器中可正常訪問,但在Node.js環境下卻返回403。
以下Node.js代碼演示了這個問題:
let response = await fetch('https://core-api.prod.blur.io/v1/prices'); const data = await response.text(); console.log(data); // 403
由于無法直接修改第三方網站配置,我們需要在Node.js端尋找解決方案。
解決方法主要有兩種:
方法一:模擬瀏覽器請求頭
瀏覽器請求通常包含特定請求頭。通過添加這些頭信息,可以模擬瀏覽器請求,從而避免403錯誤。例如:
let response = await fetch('https://core-api.prod.blur.io/v1/prices', { headers: { 'user-agent': 'Mozilla/5.0 (windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'accept': 'application/json', 'content-type': 'application/json', 'authorization': 'Bearer your_Access_token' //如果需要授權 } });
請根據瀏覽器實際請求頭調整以上代碼。your_access_token需要替換為實際的訪問令牌。
方法二:使用JSONP請求
JSONP (JSON with padding) 可以繞過CORS限制,有時能解決403錯誤。使用jsonp庫:
const jsonp = require('jsonp'); jsonp('https://core-api.prod.blur.io/v1/prices', null, (err, data) => { if (err) { console.error(err.message); } else { console.log(data); } });
這兩種方法都能嘗試解決Node.js環境下調用第三方API的403錯誤問題。 選擇哪種方法取決于具體的API和服務器配置。 如果方法一無效,可以嘗試方法二。 記住,authorization頭信息只有在API需要授權的情況下才需要添加。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END