Binance 不允许带自定义 Header 的跨域请求。解决方法:部署免费 Cloudflare Worker 中转:
https://你的worker地址/api/v3/ping,应返回 {}export default {
async fetch(request) {
if (request.method === 'OPTIONS') {
return new Response(null, { headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'GET,POST,DELETE,PUT,OPTIONS',
}});
}
const url = new URL(request.url);
const target = (url.pathname.startsWith('/fapi/') ? 'https://fapi.binance.com' : 'https://api.binance.com') + url.pathname + url.search;
const headers = new Headers();
const apiKey = request.headers.get('X-MBX-APIKEY');
if (apiKey) headers.set('X-MBX-APIKEY', apiKey);
const reqBody = ['GET','HEAD'].includes(request.method) ? undefined : await request.arrayBuffer();
if (request.headers.get('Content-Type')) headers.set('Content-Type', request.headers.get('Content-Type'));
const res = await fetch(target, { method: request.method, headers, body: reqBody });
const body = await res.text();
return new Response(body, {
status: res.status,
headers: {
'Content-Type': res.headers.get('Content-Type') || 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
},
});
}
};